3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Linker\LinkTarget
;
26 use MediaWiki\MediaWikiServices
;
29 * Represents a title within MediaWiki.
30 * Optionally may contain an interwiki designation or namespace.
31 * @note This class can fetch various kinds of data from the database;
32 * however, it does so inefficiently.
33 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
34 * and does not rely on global state or the database.
36 class Title
implements LinkTarget
{
37 /** @var HashBagOStuff */
38 static private $titleCache = null;
41 * Title::newFromText maintains a cache to avoid expensive re-normalization of
42 * commonly used titles. On a batch operation this can become a memory leak
43 * if not bounded. After hitting this many titles reset the cache.
45 const CACHE_MAX
= 1000;
48 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
49 * to use the master DB
51 const GAID_FOR_UPDATE
= 1;
54 * @name Private member variables
55 * Please use the accessor functions instead.
60 /** @var string Text form (spaces not underscores) of the main part */
61 public $mTextform = '';
63 /** @var string URL-encoded form of the main part */
64 public $mUrlform = '';
66 /** @var string Main part with underscores */
67 public $mDbkeyform = '';
69 /** @var string Database key with the initial letter in the case specified by the user */
70 protected $mUserCaseDBKey;
72 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
73 public $mNamespace = NS_MAIN
;
75 /** @var string Interwiki prefix */
76 public $mInterwiki = '';
78 /** @var bool Was this Title created from a string with a local interwiki prefix? */
79 private $mLocalInterwiki = false;
81 /** @var string Title fragment (i.e. the bit after the #) */
82 public $mFragment = '';
84 /** @var int Article ID, fetched from the link cache on demand */
85 public $mArticleID = -1;
87 /** @var bool|int ID of most recent revision */
88 protected $mLatestID = false;
91 * @var bool|string ID of the page's content model, i.e. one of the
92 * CONTENT_MODEL_XXX constants
94 public $mContentModel = false;
96 /** @var int Estimated number of revisions; null of not loaded */
97 private $mEstimateRevisions;
99 /** @var array Array of groups allowed to edit this article */
100 public $mRestrictions = [];
102 /** @var string|bool */
103 protected $mOldRestrictions = false;
105 /** @var bool Cascade restrictions on this page to included templates and images? */
106 public $mCascadeRestriction;
108 /** Caching the results of getCascadeProtectionSources */
109 public $mCascadingRestrictions;
111 /** @var array When do the restrictions on this page expire? */
112 protected $mRestrictionsExpiry = [];
114 /** @var bool Are cascading restrictions in effect on this page? */
115 protected $mHasCascadingRestrictions;
117 /** @var array Where are the cascading restrictions coming from on this page? */
118 public $mCascadeSources;
120 /** @var bool Boolean for initialisation on demand */
121 public $mRestrictionsLoaded = false;
123 /** @var string Text form including namespace/interwiki, initialised on demand */
124 protected $mPrefixedText = null;
126 /** @var mixed Cached value for getTitleProtection (create protection) */
127 public $mTitleProtection;
130 * @var int Namespace index when there is no namespace. Don't change the
131 * following default, NS_MAIN is hardcoded in several places. See bug 696.
132 * Zero except in {{transclusion}} tags.
134 public $mDefaultNamespace = NS_MAIN
;
136 /** @var int The page length, 0 for special pages */
137 protected $mLength = -1;
139 /** @var null Is the article at this title a redirect? */
140 public $mRedirect = null;
142 /** @var array Associative array of user ID -> timestamp/false */
143 private $mNotificationTimestamp = [];
145 /** @var bool Whether a page has any subpages */
146 private $mHasSubpages;
148 /** @var bool The (string) language code of the page's language and content code. */
149 private $mPageLanguage = false;
151 /** @var string|bool|null The page language code from the database, null if not saved in
152 * the database or false if not loaded, yet. */
153 private $mDbPageLanguage = false;
155 /** @var TitleValue A corresponding TitleValue object */
156 private $mTitleValue = null;
158 /** @var bool Would deleting this page be a big deletion? */
159 private $mIsBigDeletion = null;
163 * B/C kludge: provide a TitleParser for use by Title.
164 * Ideally, Title would have no methods that need this.
165 * Avoid usage of this singleton by using TitleValue
166 * and the associated services when possible.
168 * @return MediaWikiTitleCodec
170 private static function getMediaWikiTitleCodec() {
171 global $wgContLang, $wgLocalInterwikis;
173 static $titleCodec = null;
174 static $titleCodecFingerprint = null;
176 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
177 // make sure we are using the right one. To detect changes over the course
178 // of a request, we remember a fingerprint of the config used to create the
179 // codec singleton, and re-create it if the fingerprint doesn't match.
180 $fingerprint = spl_object_hash( $wgContLang ) . '|' . implode( '+', $wgLocalInterwikis );
182 if ( $fingerprint !== $titleCodecFingerprint ) {
186 if ( !$titleCodec ) {
187 $titleCodec = new MediaWikiTitleCodec(
189 GenderCache
::singleton(),
192 $titleCodecFingerprint = $fingerprint;
199 * B/C kludge: provide a TitleParser for use by Title.
200 * Ideally, Title would have no methods that need this.
201 * Avoid usage of this singleton by using TitleValue
202 * and the associated services when possible.
204 * @return TitleFormatter
206 private static function getTitleFormatter() {
207 // NOTE: we know that getMediaWikiTitleCodec() returns a MediaWikiTitleCodec,
208 // which implements TitleFormatter.
209 return self
::getMediaWikiTitleCodec();
215 function __construct() {
219 * Create a new Title from a prefixed DB key
221 * @param string $key The database key, which has underscores
222 * instead of spaces, possibly including namespace and
224 * @return Title|null Title, or null on an error
226 public static function newFromDBkey( $key ) {
228 $t->mDbkeyform
= $key;
231 $t->secureAndSplit();
233 } catch ( MalformedTitleException
$ex ) {
239 * Create a new Title from a TitleValue
241 * @param TitleValue $titleValue Assumed to be safe.
245 public static function newFromTitleValue( TitleValue
$titleValue ) {
246 return self
::newFromLinkTarget( $titleValue );
250 * Create a new Title from a LinkTarget
252 * @param LinkTarget $linkTarget Assumed to be safe.
256 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
257 if ( $linkTarget instanceof Title
) {
258 // Special case if it's already a Title object
261 return self
::makeTitle(
262 $linkTarget->getNamespace(),
263 $linkTarget->getText(),
264 $linkTarget->getFragment(),
265 $linkTarget->getInterwiki()
270 * Create a new Title from text, such as what one would find in a link. De-
271 * codes any HTML entities in the text.
273 * @param string|int|null $text The link text; spaces, prefixes, and an
274 * initial ':' indicating the main namespace are accepted.
275 * @param int $defaultNamespace The namespace to use if none is specified
276 * by a prefix. If you want to force a specific namespace even if
277 * $text might begin with a namespace prefix, use makeTitle() or
279 * @throws InvalidArgumentException
280 * @return Title|null Title or null on an error.
282 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
283 // DWIM: Integers can be passed in here when page titles are used as array keys.
284 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
285 throw new InvalidArgumentException( '$text must be a string.' );
287 if ( $text === null ) {
292 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
293 } catch ( MalformedTitleException
$ex ) {
299 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
300 * rather than returning null.
302 * The exception subclasses encode detailed information about why the title is invalid.
304 * @see Title::newFromText
307 * @param string $text Title text to check
308 * @param int $defaultNamespace
309 * @throws MalformedTitleException If the title is invalid
312 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
313 if ( is_object( $text ) ) {
314 throw new MWException( '$text must be a string, given an object' );
317 $titleCache = self
::getTitleCache();
319 // Wiki pages often contain multiple links to the same page.
320 // Title normalization and parsing can become expensive on pages with many
321 // links, so we can save a little time by caching them.
322 // In theory these are value objects and won't get changed...
323 if ( $defaultNamespace == NS_MAIN
) {
324 $t = $titleCache->get( $text );
330 // Convert things like é ā or 〗 into normalized (bug 14952) text
331 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
334 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
335 $t->mDefaultNamespace
= intval( $defaultNamespace );
337 $t->secureAndSplit();
338 if ( $defaultNamespace == NS_MAIN
) {
339 $titleCache->set( $text, $t );
345 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
347 * Example of wrong and broken code:
348 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
350 * Example of right code:
351 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
353 * Create a new Title from URL-encoded text. Ensures that
354 * the given title's length does not exceed the maximum.
356 * @param string $url The title, as might be taken from a URL
357 * @return Title|null The new object, or null on an error
359 public static function newFromURL( $url ) {
362 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
363 # but some URLs used it as a space replacement and they still come
364 # from some external search tools.
365 if ( strpos( self
::legalChars(), '+' ) === false ) {
366 $url = strtr( $url, '+', ' ' );
369 $t->mDbkeyform
= strtr( $url, ' ', '_' );
372 $t->secureAndSplit();
374 } catch ( MalformedTitleException
$ex ) {
380 * @return HashBagOStuff
382 private static function getTitleCache() {
383 if ( self
::$titleCache == null ) {
384 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
386 return self
::$titleCache;
390 * Returns a list of fields that are to be selected for initializing Title
391 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
392 * whether to include page_content_model.
396 protected static function getSelectFields() {
397 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
400 'page_namespace', 'page_title', 'page_id',
401 'page_len', 'page_is_redirect', 'page_latest',
404 if ( $wgContentHandlerUseDB ) {
405 $fields[] = 'page_content_model';
408 if ( $wgPageLanguageUseDB ) {
409 $fields[] = 'page_lang';
416 * Create a new Title from an article ID
418 * @param int $id The page_id corresponding to the Title to create
419 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
420 * @return Title|null The new object, or null on an error
422 public static function newFromID( $id, $flags = 0 ) {
423 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
424 $row = $db->selectRow(
426 self
::getSelectFields(),
427 [ 'page_id' => $id ],
430 if ( $row !== false ) {
431 $title = Title
::newFromRow( $row );
439 * Make an array of titles from an array of IDs
441 * @param int[] $ids Array of IDs
442 * @return Title[] Array of Titles
444 public static function newFromIDs( $ids ) {
445 if ( !count( $ids ) ) {
448 $dbr = wfGetDB( DB_SLAVE
);
452 self
::getSelectFields(),
453 [ 'page_id' => $ids ],
458 foreach ( $res as $row ) {
459 $titles[] = Title
::newFromRow( $row );
465 * Make a Title object from a DB row
467 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
468 * @return Title Corresponding Title
470 public static function newFromRow( $row ) {
471 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
472 $t->loadFromRow( $row );
477 * Load Title object fields from a DB row.
478 * If false is given, the title will be treated as non-existing.
480 * @param stdClass|bool $row Database row
482 public function loadFromRow( $row ) {
483 if ( $row ) { // page found
484 if ( isset( $row->page_id
) ) {
485 $this->mArticleID
= (int)$row->page_id
;
487 if ( isset( $row->page_len
) ) {
488 $this->mLength
= (int)$row->page_len
;
490 if ( isset( $row->page_is_redirect
) ) {
491 $this->mRedirect
= (bool)$row->page_is_redirect
;
493 if ( isset( $row->page_latest
) ) {
494 $this->mLatestID
= (int)$row->page_latest
;
496 if ( isset( $row->page_content_model
) ) {
497 $this->mContentModel
= strval( $row->page_content_model
);
499 $this->mContentModel
= false; # initialized lazily in getContentModel()
501 if ( isset( $row->page_lang
) ) {
502 $this->mDbPageLanguage
= (string)$row->page_lang
;
504 if ( isset( $row->page_restrictions
) ) {
505 $this->mOldRestrictions
= $row->page_restrictions
;
507 } else { // page not found
508 $this->mArticleID
= 0;
510 $this->mRedirect
= false;
511 $this->mLatestID
= 0;
512 $this->mContentModel
= false; # initialized lazily in getContentModel()
517 * Create a new Title from a namespace index and a DB key.
518 * It's assumed that $ns and $title are *valid*, for instance when
519 * they came directly from the database or a special page name.
520 * For convenience, spaces are converted to underscores so that
521 * eg user_text fields can be used directly.
523 * @param int $ns The namespace of the article
524 * @param string $title The unprefixed database key form
525 * @param string $fragment The link fragment (after the "#")
526 * @param string $interwiki The interwiki prefix
527 * @return Title The new object
529 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
531 $t->mInterwiki
= $interwiki;
532 $t->mFragment
= $fragment;
533 $t->mNamespace
= $ns = intval( $ns );
534 $t->mDbkeyform
= strtr( $title, ' ', '_' );
535 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
536 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
537 $t->mTextform
= strtr( $title, '_', ' ' );
538 $t->mContentModel
= false; # initialized lazily in getContentModel()
543 * Create a new Title from a namespace index and a DB key.
544 * The parameters will be checked for validity, which is a bit slower
545 * than makeTitle() but safer for user-provided data.
547 * @param int $ns The namespace of the article
548 * @param string $title Database key form
549 * @param string $fragment The link fragment (after the "#")
550 * @param string $interwiki Interwiki prefix
551 * @return Title|null The new object, or null on an error
553 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
554 if ( !MWNamespace
::exists( $ns ) ) {
559 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
562 $t->secureAndSplit();
564 } catch ( MalformedTitleException
$ex ) {
570 * Create a new Title for the Main Page
572 * @return Title The new object
574 public static function newMainPage() {
575 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
576 // Don't give fatal errors if the message is broken
578 $title = Title
::newFromText( 'Main Page' );
584 * Get the prefixed DB key associated with an ID
586 * @param int $id The page_id of the article
587 * @return Title|null An object representing the article, or null if no such article was found
589 public static function nameOf( $id ) {
590 $dbr = wfGetDB( DB_SLAVE
);
592 $s = $dbr->selectRow(
594 [ 'page_namespace', 'page_title' ],
595 [ 'page_id' => $id ],
598 if ( $s === false ) {
602 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
607 * Get a regex character class describing the legal characters in a link
609 * @return string The list of characters, not delimited
611 public static function legalChars() {
612 global $wgLegalTitleChars;
613 return $wgLegalTitleChars;
617 * Returns a simple regex that will match on characters and sequences invalid in titles.
618 * Note that this doesn't pick up many things that could be wrong with titles, but that
619 * replacing this regex with something valid will make many titles valid.
621 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
623 * @return string Regex string
625 static function getTitleInvalidRegex() {
626 wfDeprecated( __METHOD__
, '1.25' );
627 return MediaWikiTitleCodec
::getTitleInvalidRegex();
631 * Utility method for converting a character sequence from bytes to Unicode.
633 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
634 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
636 * @param string $byteClass
639 public static function convertByteClassToUnicodeClass( $byteClass ) {
640 $length = strlen( $byteClass );
642 $x0 = $x1 = $x2 = '';
644 $d0 = $d1 = $d2 = '';
645 // Decoded integer codepoints
646 $ord0 = $ord1 = $ord2 = 0;
648 $r0 = $r1 = $r2 = '';
652 $allowUnicode = false;
653 for ( $pos = 0; $pos < $length; $pos++
) {
654 // Shift the queues down
663 // Load the current input token and decoded values
664 $inChar = $byteClass[$pos];
665 if ( $inChar == '\\' ) {
666 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
667 $x0 = $inChar . $m[0];
668 $d0 = chr( hexdec( $m[1] ) );
669 $pos +
= strlen( $m[0] );
670 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
671 $x0 = $inChar . $m[0];
672 $d0 = chr( octdec( $m[0] ) );
673 $pos +
= strlen( $m[0] );
674 } elseif ( $pos +
1 >= $length ) {
677 $d0 = $byteClass[$pos +
1];
685 // Load the current re-encoded value
686 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
687 $r0 = sprintf( '\x%02x', $ord0 );
688 } elseif ( $ord0 >= 0x80 ) {
689 // Allow unicode if a single high-bit character appears
690 $r0 = sprintf( '\x%02x', $ord0 );
691 $allowUnicode = true;
692 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
698 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
700 if ( $ord2 > $ord0 ) {
702 } elseif ( $ord0 >= 0x80 ) {
704 $allowUnicode = true;
705 if ( $ord2 < 0x80 ) {
706 // Keep the non-unicode section of the range
713 // Reset state to the initial value
714 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
715 } elseif ( $ord2 < 0x80 ) {
720 if ( $ord1 < 0x80 ) {
723 if ( $ord0 < 0x80 ) {
726 if ( $allowUnicode ) {
727 $out .= '\u0080-\uFFFF';
733 * Make a prefixed DB key from a DB key and a namespace index
735 * @param int $ns Numerical representation of the namespace
736 * @param string $title The DB key form the title
737 * @param string $fragment The link fragment (after the "#")
738 * @param string $interwiki The interwiki prefix
739 * @param bool $canonicalNamespace If true, use the canonical name for
740 * $ns instead of the localized version.
741 * @return string The prefixed form of the title
743 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
744 $canonicalNamespace = false
748 if ( $canonicalNamespace ) {
749 $namespace = MWNamespace
::getCanonicalName( $ns );
751 $namespace = $wgContLang->getNsText( $ns );
753 $name = $namespace == '' ?
$title : "$namespace:$title";
754 if ( strval( $interwiki ) != '' ) {
755 $name = "$interwiki:$name";
757 if ( strval( $fragment ) != '' ) {
758 $name .= '#' . $fragment;
764 * Escape a text fragment, say from a link, for a URL
766 * @param string $fragment Containing a URL or link fragment (after the "#")
767 * @return string Escaped string
769 static function escapeFragmentForURL( $fragment ) {
770 # Note that we don't urlencode the fragment. urlencoded Unicode
771 # fragments appear not to work in IE (at least up to 7) or in at least
772 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
773 # to care if they aren't encoded.
774 return Sanitizer
::escapeId( $fragment, 'noninitial' );
778 * Callback for usort() to do title sorts by (namespace, title)
783 * @return int Result of string comparison, or namespace comparison
785 public static function compare( $a, $b ) {
786 if ( $a->getNamespace() == $b->getNamespace() ) {
787 return strcmp( $a->getText(), $b->getText() );
789 return $a->getNamespace() - $b->getNamespace();
794 * Determine whether the object refers to a page within
795 * this project (either this wiki or a wiki with a local
796 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
798 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
800 public function isLocal() {
801 if ( $this->isExternal() ) {
802 $iw = Interwiki
::fetch( $this->mInterwiki
);
804 return $iw->isLocal();
811 * Is this Title interwiki?
815 public function isExternal() {
816 return $this->mInterwiki
!== '';
820 * Get the interwiki prefix
822 * Use Title::isExternal to check if a interwiki is set
824 * @return string Interwiki prefix
826 public function getInterwiki() {
827 return $this->mInterwiki
;
831 * Was this a local interwiki link?
835 public function wasLocalInterwiki() {
836 return $this->mLocalInterwiki
;
840 * Determine whether the object refers to a page within
841 * this project and is transcludable.
843 * @return bool True if this is transcludable
845 public function isTrans() {
846 if ( !$this->isExternal() ) {
850 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
854 * Returns the DB name of the distant wiki which owns the object.
856 * @return string The DB name
858 public function getTransWikiID() {
859 if ( !$this->isExternal() ) {
863 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
867 * Get a TitleValue object representing this Title.
869 * @note Not all valid Titles have a corresponding valid TitleValue
870 * (e.g. TitleValues cannot represent page-local links that have a
871 * fragment but no title text).
873 * @return TitleValue|null
875 public function getTitleValue() {
876 if ( $this->mTitleValue
=== null ) {
878 $this->mTitleValue
= new TitleValue(
879 $this->getNamespace(),
881 $this->getFragment(),
882 $this->getInterwiki()
884 } catch ( InvalidArgumentException
$ex ) {
885 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
886 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
890 return $this->mTitleValue
;
894 * Get the text form (spaces not underscores) of the main part
896 * @return string Main part of the title
898 public function getText() {
899 return $this->mTextform
;
903 * Get the URL-encoded form of the main part
905 * @return string Main part of the title, URL-encoded
907 public function getPartialURL() {
908 return $this->mUrlform
;
912 * Get the main part with underscores
914 * @return string Main part of the title, with underscores
916 public function getDBkey() {
917 return $this->mDbkeyform
;
921 * Get the DB key with the initial letter case as specified by the user
923 * @return string DB key
925 function getUserCaseDBKey() {
926 if ( !is_null( $this->mUserCaseDBKey
) ) {
927 return $this->mUserCaseDBKey
;
929 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
930 return $this->mDbkeyform
;
935 * Get the namespace index, i.e. one of the NS_xxxx constants.
937 * @return int Namespace index
939 public function getNamespace() {
940 return $this->mNamespace
;
944 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
946 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
947 * @return string Content model id
949 public function getContentModel( $flags = 0 ) {
950 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
951 $linkCache = LinkCache
::singleton();
952 $linkCache->addLinkObj( $this ); # in case we already had an article ID
953 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
956 if ( !$this->mContentModel
) {
957 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
960 return $this->mContentModel
;
964 * Convenience method for checking a title's content model name
966 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
967 * @return bool True if $this->getContentModel() == $id
969 public function hasContentModel( $id ) {
970 return $this->getContentModel() == $id;
974 * Get the namespace text
976 * @return string Namespace text
978 public function getNsText() {
979 if ( $this->isExternal() ) {
980 // This probably shouldn't even happen,
981 // but for interwiki transclusion it sometimes does.
982 // Use the canonical namespaces if possible to try to
983 // resolve a foreign namespace.
984 if ( MWNamespace
::exists( $this->mNamespace
) ) {
985 return MWNamespace
::getCanonicalName( $this->mNamespace
);
990 $formatter = self
::getTitleFormatter();
991 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
992 } catch ( InvalidArgumentException
$ex ) {
993 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
999 * Get the namespace text of the subject (rather than talk) page
1001 * @return string Namespace text
1003 public function getSubjectNsText() {
1005 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1009 * Get the namespace text of the talk page
1011 * @return string Namespace text
1013 public function getTalkNsText() {
1015 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1019 * Could this title have a corresponding talk page?
1023 public function canTalk() {
1024 return MWNamespace
::canTalk( $this->mNamespace
);
1028 * Is this in a namespace that allows actual pages?
1032 public function canExist() {
1033 return $this->mNamespace
>= NS_MAIN
;
1037 * Can this title be added to a user's watchlist?
1041 public function isWatchable() {
1042 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1046 * Returns true if this is a special page.
1050 public function isSpecialPage() {
1051 return $this->getNamespace() == NS_SPECIAL
;
1055 * Returns true if this title resolves to the named special page
1057 * @param string $name The special page name
1060 public function isSpecial( $name ) {
1061 if ( $this->isSpecialPage() ) {
1062 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1063 if ( $name == $thisName ) {
1071 * If the Title refers to a special page alias which is not the local default, resolve
1072 * the alias, and localise the name as necessary. Otherwise, return $this
1076 public function fixSpecialName() {
1077 if ( $this->isSpecialPage() ) {
1078 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1079 if ( $canonicalName ) {
1080 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1081 if ( $localName != $this->mDbkeyform
) {
1082 return Title
::makeTitle( NS_SPECIAL
, $localName );
1090 * Returns true if the title is inside the specified namespace.
1092 * Please make use of this instead of comparing to getNamespace()
1093 * This function is much more resistant to changes we may make
1094 * to namespaces than code that makes direct comparisons.
1095 * @param int $ns The namespace
1099 public function inNamespace( $ns ) {
1100 return MWNamespace
::equals( $this->getNamespace(), $ns );
1104 * Returns true if the title is inside one of the specified namespaces.
1106 * @param int $namespaces,... The namespaces to check for
1110 public function inNamespaces( /* ... */ ) {
1111 $namespaces = func_get_args();
1112 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1113 $namespaces = $namespaces[0];
1116 foreach ( $namespaces as $ns ) {
1117 if ( $this->inNamespace( $ns ) ) {
1126 * Returns true if the title has the same subject namespace as the
1127 * namespace specified.
1128 * For example this method will take NS_USER and return true if namespace
1129 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1130 * as their subject namespace.
1132 * This is MUCH simpler than individually testing for equivalence
1133 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1138 public function hasSubjectNamespace( $ns ) {
1139 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1143 * Is this Title in a namespace which contains content?
1144 * In other words, is this a content page, for the purposes of calculating
1149 public function isContentPage() {
1150 return MWNamespace
::isContent( $this->getNamespace() );
1154 * Would anybody with sufficient privileges be able to move this page?
1155 * Some pages just aren't movable.
1159 public function isMovable() {
1160 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1161 // Interwiki title or immovable namespace. Hooks don't get to override here
1166 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1171 * Is this the mainpage?
1172 * @note Title::newFromText seems to be sufficiently optimized by the title
1173 * cache that we don't need to over-optimize by doing direct comparisons and
1174 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1175 * ends up reporting something differently than $title->isMainPage();
1180 public function isMainPage() {
1181 return $this->equals( Title
::newMainPage() );
1185 * Is this a subpage?
1189 public function isSubpage() {
1190 return MWNamespace
::hasSubpages( $this->mNamespace
)
1191 ?
strpos( $this->getText(), '/' ) !== false
1196 * Is this a conversion table for the LanguageConverter?
1200 public function isConversionTable() {
1201 // @todo ConversionTable should become a separate content model.
1203 return $this->getNamespace() == NS_MEDIAWIKI
&&
1204 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1208 * Does that page contain wikitext, or it is JS, CSS or whatever?
1212 public function isWikitextPage() {
1213 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1217 * Could this page contain custom CSS or JavaScript for the global UI.
1218 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1219 * or CONTENT_MODEL_JAVASCRIPT.
1221 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1224 * Note that this method should not return true for pages that contain and
1225 * show "inactive" CSS or JS.
1228 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1230 public function isCssOrJsPage() {
1231 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1232 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1233 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1235 # @note This hook is also called in ContentHandler::getDefaultModel.
1236 # It's called here again to make sure hook functions can force this
1237 # method to return true even outside the MediaWiki namespace.
1239 Hooks
::run( 'TitleIsCssOrJsPage', [ $this, &$isCssOrJsPage ], '1.25' );
1241 return $isCssOrJsPage;
1245 * Is this a .css or .js subpage of a user page?
1247 * @todo FIXME: Rename to isUserConfigPage()
1249 public function isCssJsSubpage() {
1250 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1251 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1252 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1256 * Trim down a .css or .js subpage title to get the corresponding skin name
1258 * @return string Containing skin name from .css or .js subpage title
1260 public function getSkinFromCssJsSubpage() {
1261 $subpage = explode( '/', $this->mTextform
);
1262 $subpage = $subpage[count( $subpage ) - 1];
1263 $lastdot = strrpos( $subpage, '.' );
1264 if ( $lastdot === false ) {
1265 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1267 return substr( $subpage, 0, $lastdot );
1271 * Is this a .css subpage of a user page?
1275 public function isCssSubpage() {
1276 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1277 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1281 * Is this a .js subpage of a user page?
1285 public function isJsSubpage() {
1286 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1287 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1291 * Is this a talk page of some sort?
1295 public function isTalkPage() {
1296 return MWNamespace
::isTalk( $this->getNamespace() );
1300 * Get a Title object associated with the talk page of this article
1302 * @return Title The object for the talk page
1304 public function getTalkPage() {
1305 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1309 * Get a title object associated with the subject page of this
1312 * @return Title The object for the subject page
1314 public function getSubjectPage() {
1315 // Is this the same title?
1316 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1317 if ( $this->getNamespace() == $subjectNS ) {
1320 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1324 * Get the other title for this page, if this is a subject page
1325 * get the talk page, if it is a subject page get the talk page
1328 * @throws MWException
1331 public function getOtherPage() {
1332 if ( $this->isSpecialPage() ) {
1333 throw new MWException( 'Special pages cannot have other pages' );
1335 if ( $this->isTalkPage() ) {
1336 return $this->getSubjectPage();
1338 return $this->getTalkPage();
1343 * Get the default namespace index, for when there is no namespace
1345 * @return int Default namespace index
1347 public function getDefaultNamespace() {
1348 return $this->mDefaultNamespace
;
1352 * Get the Title fragment (i.e.\ the bit after the #) in text form
1354 * Use Title::hasFragment to check for a fragment
1356 * @return string Title fragment
1358 public function getFragment() {
1359 return $this->mFragment
;
1363 * Check if a Title fragment is set
1368 public function hasFragment() {
1369 return $this->mFragment
!== '';
1373 * Get the fragment in URL form, including the "#" character if there is one
1374 * @return string Fragment in URL form
1376 public function getFragmentForURL() {
1377 if ( !$this->hasFragment() ) {
1380 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1385 * Set the fragment for this title. Removes the first character from the
1386 * specified fragment before setting, so it assumes you're passing it with
1389 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1390 * or Title::createFragmentTarget().
1391 * Still in active use privately.
1394 * @param string $fragment Text
1396 public function setFragment( $fragment ) {
1397 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1401 * Creates a new Title for a different fragment of the same page.
1404 * @param string $fragment
1407 public function createFragmentTarget( $fragment ) {
1408 return self
::makeTitle(
1409 $this->getNamespace(),
1412 $this->getInterwiki()
1418 * Prefix some arbitrary text with the namespace or interwiki prefix
1421 * @param string $name The text
1422 * @return string The prefixed text
1424 private function prefix( $name ) {
1426 if ( $this->isExternal() ) {
1427 $p = $this->mInterwiki
. ':';
1430 if ( 0 != $this->mNamespace
) {
1431 $p .= $this->getNsText() . ':';
1437 * Get the prefixed database key form
1439 * @return string The prefixed title, with underscores and
1440 * any interwiki and namespace prefixes
1442 public function getPrefixedDBkey() {
1443 $s = $this->prefix( $this->mDbkeyform
);
1444 $s = strtr( $s, ' ', '_' );
1449 * Get the prefixed title with spaces.
1450 * This is the form usually used for display
1452 * @return string The prefixed title, with spaces
1454 public function getPrefixedText() {
1455 if ( $this->mPrefixedText
=== null ) {
1456 $s = $this->prefix( $this->mTextform
);
1457 $s = strtr( $s, '_', ' ' );
1458 $this->mPrefixedText
= $s;
1460 return $this->mPrefixedText
;
1464 * Return a string representation of this title
1466 * @return string Representation of this title
1468 public function __toString() {
1469 return $this->getPrefixedText();
1473 * Get the prefixed title with spaces, plus any fragment
1474 * (part beginning with '#')
1476 * @return string The prefixed title, with spaces and the fragment, including '#'
1478 public function getFullText() {
1479 $text = $this->getPrefixedText();
1480 if ( $this->hasFragment() ) {
1481 $text .= '#' . $this->getFragment();
1487 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1491 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1495 * @return string Root name
1498 public function getRootText() {
1499 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1500 return $this->getText();
1503 return strtok( $this->getText(), '/' );
1507 * Get the root page name title, i.e. the leftmost part before any slashes
1511 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1512 * # returns: Title{User:Foo}
1515 * @return Title Root title
1518 public function getRootTitle() {
1519 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1523 * Get the base page name without a namespace, i.e. the part before the subpage name
1527 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1528 * # returns: 'Foo/Bar'
1531 * @return string Base name
1533 public function getBaseText() {
1534 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1535 return $this->getText();
1538 $parts = explode( '/', $this->getText() );
1539 # Don't discard the real title if there's no subpage involved
1540 if ( count( $parts ) > 1 ) {
1541 unset( $parts[count( $parts ) - 1] );
1543 return implode( '/', $parts );
1547 * Get the base page name title, i.e. the part before the subpage name
1551 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1552 * # returns: Title{User:Foo/Bar}
1555 * @return Title Base title
1558 public function getBaseTitle() {
1559 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1563 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1567 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1571 * @return string Subpage name
1573 public function getSubpageText() {
1574 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1575 return $this->mTextform
;
1577 $parts = explode( '/', $this->mTextform
);
1578 return $parts[count( $parts ) - 1];
1582 * Get the title for a subpage of the current page
1586 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1587 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1590 * @param string $text The subpage name to add to the title
1591 * @return Title Subpage title
1594 public function getSubpage( $text ) {
1595 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1599 * Get a URL-encoded form of the subpage text
1601 * @return string URL-encoded subpage name
1603 public function getSubpageUrlForm() {
1604 $text = $this->getSubpageText();
1605 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1610 * Get a URL-encoded title (not an actual URL) including interwiki
1612 * @return string The URL-encoded form
1614 public function getPrefixedURL() {
1615 $s = $this->prefix( $this->mDbkeyform
);
1616 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1621 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1622 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1623 * second argument named variant. This was deprecated in favor
1624 * of passing an array of option with a "variant" key
1625 * Once $query2 is removed for good, this helper can be dropped
1626 * and the wfArrayToCgi moved to getLocalURL();
1628 * @since 1.19 (r105919)
1629 * @param array|string $query
1630 * @param bool $query2
1633 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1634 if ( $query2 !== false ) {
1635 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1636 "method called with a second parameter is deprecated. Add your " .
1637 "parameter to an array passed as the first parameter.", "1.19" );
1639 if ( is_array( $query ) ) {
1640 $query = wfArrayToCgi( $query );
1643 if ( is_string( $query2 ) ) {
1644 // $query2 is a string, we will consider this to be
1645 // a deprecated $variant argument and add it to the query
1646 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1648 $query2 = wfArrayToCgi( $query2 );
1650 // If we have $query content add a & to it first
1654 // Now append the queries together
1661 * Get a real URL referring to this title, with interwiki link and
1664 * @see self::getLocalURL for the arguments.
1666 * @param array|string $query
1667 * @param bool $query2
1668 * @param string $proto Protocol type to use in URL
1669 * @return string The URL
1671 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1672 $query = self
::fixUrlQueryArgs( $query, $query2 );
1674 # Hand off all the decisions on urls to getLocalURL
1675 $url = $this->getLocalURL( $query );
1677 # Expand the url to make it a full url. Note that getLocalURL has the
1678 # potential to output full urls for a variety of reasons, so we use
1679 # wfExpandUrl instead of simply prepending $wgServer
1680 $url = wfExpandUrl( $url, $proto );
1682 # Finally, add the fragment.
1683 $url .= $this->getFragmentForURL();
1685 Hooks
::run( 'GetFullURL', [ &$this, &$url, $query ] );
1690 * Get a URL with no fragment or server name (relative URL) from a Title object.
1691 * If this page is generated with action=render, however,
1692 * $wgServer is prepended to make an absolute URL.
1694 * @see self::getFullURL to always get an absolute URL.
1695 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1696 * valid to link, locally, to the current Title.
1697 * @see self::newFromText to produce a Title object.
1699 * @param string|array $query An optional query string,
1700 * not used for interwiki links. Can be specified as an associative array as well,
1701 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1702 * Some query patterns will trigger various shorturl path replacements.
1703 * @param array $query2 An optional secondary query array. This one MUST
1704 * be an array. If a string is passed it will be interpreted as a deprecated
1705 * variant argument and urlencoded into a variant= argument.
1706 * This second query argument will be added to the $query
1707 * The second parameter is deprecated since 1.19. Pass it as a key,value
1708 * pair in the first parameter array instead.
1710 * @return string String of the URL.
1712 public function getLocalURL( $query = '', $query2 = false ) {
1713 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1715 $query = self
::fixUrlQueryArgs( $query, $query2 );
1717 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1719 $namespace = $this->getNsText();
1720 if ( $namespace != '' ) {
1721 # Can this actually happen? Interwikis shouldn't be parsed.
1722 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1725 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1726 $url = wfAppendQuery( $url, $query );
1728 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1729 if ( $query == '' ) {
1730 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1731 Hooks
::run( 'GetLocalURL::Article', [ &$this, &$url ] );
1733 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1737 if ( !empty( $wgActionPaths )
1738 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1740 $action = urldecode( $matches[2] );
1741 if ( isset( $wgActionPaths[$action] ) ) {
1742 $query = $matches[1];
1743 if ( isset( $matches[4] ) ) {
1744 $query .= $matches[4];
1746 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1747 if ( $query != '' ) {
1748 $url = wfAppendQuery( $url, $query );
1754 && $wgVariantArticlePath
1755 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1756 && $this->getPageLanguage()->hasVariants()
1757 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1759 $variant = urldecode( $matches[1] );
1760 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1761 // Only do the variant replacement if the given variant is a valid
1762 // variant for the page's language.
1763 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1764 $url = str_replace( '$1', $dbkey, $url );
1768 if ( $url === false ) {
1769 if ( $query == '-' ) {
1772 $url = "{$wgScript}?title={$dbkey}&{$query}";
1776 Hooks
::run( 'GetLocalURL::Internal', [ &$this, &$url, $query ] );
1778 // @todo FIXME: This causes breakage in various places when we
1779 // actually expected a local URL and end up with dupe prefixes.
1780 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1781 $url = $wgServer . $url;
1784 Hooks
::run( 'GetLocalURL', [ &$this, &$url, $query ] );
1789 * Get a URL that's the simplest URL that will be valid to link, locally,
1790 * to the current Title. It includes the fragment, but does not include
1791 * the server unless action=render is used (or the link is external). If
1792 * there's a fragment but the prefixed text is empty, we just return a link
1795 * The result obviously should not be URL-escaped, but does need to be
1796 * HTML-escaped if it's being output in HTML.
1798 * @param array $query
1799 * @param bool $query2
1800 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1801 * @see self::getLocalURL for the arguments.
1802 * @return string The URL
1804 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1805 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1806 $ret = $this->getFullURL( $query, $query2, $proto );
1807 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1808 $ret = $this->getFragmentForURL();
1810 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1816 * Get the URL form for an internal link.
1817 * - Used in various CDN-related code, in case we have a different
1818 * internal hostname for the server from the exposed one.
1820 * This uses $wgInternalServer to qualify the path, or $wgServer
1821 * if $wgInternalServer is not set. If the server variable used is
1822 * protocol-relative, the URL will be expanded to http://
1824 * @see self::getLocalURL for the arguments.
1825 * @return string The URL
1827 public function getInternalURL( $query = '', $query2 = false ) {
1828 global $wgInternalServer, $wgServer;
1829 $query = self
::fixUrlQueryArgs( $query, $query2 );
1830 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1831 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1832 Hooks
::run( 'GetInternalURL', [ &$this, &$url, $query ] );
1837 * Get the URL for a canonical link, for use in things like IRC and
1838 * e-mail notifications. Uses $wgCanonicalServer and the
1839 * GetCanonicalURL hook.
1841 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1843 * @see self::getLocalURL for the arguments.
1844 * @return string The URL
1847 public function getCanonicalURL( $query = '', $query2 = false ) {
1848 $query = self
::fixUrlQueryArgs( $query, $query2 );
1849 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1850 Hooks
::run( 'GetCanonicalURL', [ &$this, &$url, $query ] );
1855 * Get the edit URL for this Title
1857 * @return string The URL, or a null string if this is an interwiki link
1859 public function getEditURL() {
1860 if ( $this->isExternal() ) {
1863 $s = $this->getLocalURL( 'action=edit' );
1869 * Can $user perform $action on this page?
1870 * This skips potentially expensive cascading permission checks
1871 * as well as avoids expensive error formatting
1873 * Suitable for use for nonessential UI controls in common cases, but
1874 * _not_ for functional access control.
1876 * May provide false positives, but should never provide a false negative.
1878 * @param string $action Action that permission needs to be checked for
1879 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1882 public function quickUserCan( $action, $user = null ) {
1883 return $this->userCan( $action, $user, false );
1887 * Can $user perform $action on this page?
1889 * @param string $action Action that permission needs to be checked for
1890 * @param User $user User to check (since 1.19); $wgUser will be used if not
1892 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1895 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1896 if ( !$user instanceof User
) {
1901 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1905 * Can $user perform $action on this page?
1907 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1909 * @param string $action Action that permission needs to be checked for
1910 * @param User $user User to check
1911 * @param string $rigor One of (quick,full,secure)
1912 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1913 * - full : does cheap and expensive checks possibly from a slave
1914 * - secure : does cheap and expensive checks, using the master as needed
1915 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1916 * whose corresponding errors may be ignored.
1917 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1919 public function getUserPermissionsErrors(
1920 $action, $user, $rigor = 'secure', $ignoreErrors = []
1922 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1924 // Remove the errors being ignored.
1925 foreach ( $errors as $index => $error ) {
1926 $errKey = is_array( $error ) ?
$error[0] : $error;
1928 if ( in_array( $errKey, $ignoreErrors ) ) {
1929 unset( $errors[$index] );
1931 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1932 unset( $errors[$index] );
1940 * Permissions checks that fail most often, and which are easiest to test.
1942 * @param string $action The action to check
1943 * @param User $user User to check
1944 * @param array $errors List of current errors
1945 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1946 * @param bool $short Short circuit on first error
1948 * @return array List of errors
1950 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1951 if ( !Hooks
::run( 'TitleQuickPermissions',
1952 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
1957 if ( $action == 'create' ) {
1959 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1960 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1962 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
1964 } elseif ( $action == 'move' ) {
1965 if ( !$user->isAllowed( 'move-rootuserpages' )
1966 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1967 // Show user page-specific message only if the user can move other pages
1968 $errors[] = [ 'cant-move-user-page' ];
1971 // Check if user is allowed to move files if it's a file
1972 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1973 $errors[] = [ 'movenotallowedfile' ];
1976 // Check if user is allowed to move category pages if it's a category page
1977 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1978 $errors[] = [ 'cant-move-category-page' ];
1981 if ( !$user->isAllowed( 'move' ) ) {
1982 // User can't move anything
1983 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1984 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1985 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1986 // custom message if logged-in users without any special rights can move
1987 $errors[] = [ 'movenologintext' ];
1989 $errors[] = [ 'movenotallowed' ];
1992 } elseif ( $action == 'move-target' ) {
1993 if ( !$user->isAllowed( 'move' ) ) {
1994 // User can't move anything
1995 $errors[] = [ 'movenotallowed' ];
1996 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1997 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1998 // Show user page-specific message only if the user can move other pages
1999 $errors[] = [ 'cant-move-to-user-page' ];
2000 } elseif ( !$user->isAllowed( 'move-categorypages' )
2001 && $this->mNamespace
== NS_CATEGORY
) {
2002 // Show category page-specific message only if the user can move other pages
2003 $errors[] = [ 'cant-move-to-category-page' ];
2005 } elseif ( !$user->isAllowed( $action ) ) {
2006 $errors[] = $this->missingPermissionError( $action, $short );
2013 * Add the resulting error code to the errors array
2015 * @param array $errors List of current errors
2016 * @param array $result Result of errors
2018 * @return array List of errors
2020 private function resultToError( $errors, $result ) {
2021 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2022 // A single array representing an error
2023 $errors[] = $result;
2024 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2025 // A nested array representing multiple errors
2026 $errors = array_merge( $errors, $result );
2027 } elseif ( $result !== '' && is_string( $result ) ) {
2028 // A string representing a message-id
2029 $errors[] = [ $result ];
2030 } elseif ( $result instanceof MessageSpecifier
) {
2031 // A message specifier representing an error
2032 $errors[] = [ $result ];
2033 } elseif ( $result === false ) {
2034 // a generic "We don't want them to do that"
2035 $errors[] = [ 'badaccess-group0' ];
2041 * Check various permission hooks
2043 * @param string $action The action to check
2044 * @param User $user User to check
2045 * @param array $errors List of current errors
2046 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2047 * @param bool $short Short circuit on first error
2049 * @return array List of errors
2051 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2052 // Use getUserPermissionsErrors instead
2054 if ( !Hooks
::run( 'userCan', [ &$this, &$user, $action, &$result ] ) ) {
2055 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2057 // Check getUserPermissionsErrors hook
2058 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$this, &$user, $action, &$result ] ) ) {
2059 $errors = $this->resultToError( $errors, $result );
2061 // Check getUserPermissionsErrorsExpensive hook
2064 && !( $short && count( $errors ) > 0 )
2065 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$this, &$user, $action, &$result ] )
2067 $errors = $this->resultToError( $errors, $result );
2074 * Check permissions on special pages & namespaces
2076 * @param string $action The action to check
2077 * @param User $user User to check
2078 * @param array $errors List of current errors
2079 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2080 * @param bool $short Short circuit on first error
2082 * @return array List of errors
2084 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2085 # Only 'createaccount' can be performed on special pages,
2086 # which don't actually exist in the DB.
2087 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2088 $errors[] = [ 'ns-specialprotected' ];
2091 # Check $wgNamespaceProtection for restricted namespaces
2092 if ( $this->isNamespaceProtected( $user ) ) {
2093 $ns = $this->mNamespace
== NS_MAIN ?
2094 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2095 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2096 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2103 * Check CSS/JS sub-page permissions
2105 * @param string $action The action to check
2106 * @param User $user User to check
2107 * @param array $errors List of current errors
2108 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2109 * @param bool $short Short circuit on first error
2111 * @return array List of errors
2113 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2114 # Protect css/js subpages of user pages
2115 # XXX: this might be better using restrictions
2116 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2117 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2118 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2119 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2120 $errors[] = [ 'mycustomcssprotected', $action ];
2121 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2122 $errors[] = [ 'mycustomjsprotected', $action ];
2125 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2126 $errors[] = [ 'customcssprotected', $action ];
2127 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2128 $errors[] = [ 'customjsprotected', $action ];
2137 * Check against page_restrictions table requirements on this
2138 * page. The user must possess all required rights for this
2141 * @param string $action The action to check
2142 * @param User $user User to check
2143 * @param array $errors List of current errors
2144 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2145 * @param bool $short Short circuit on first error
2147 * @return array List of errors
2149 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2150 foreach ( $this->getRestrictions( $action ) as $right ) {
2151 // Backwards compatibility, rewrite sysop -> editprotected
2152 if ( $right == 'sysop' ) {
2153 $right = 'editprotected';
2155 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2156 if ( $right == 'autoconfirmed' ) {
2157 $right = 'editsemiprotected';
2159 if ( $right == '' ) {
2162 if ( !$user->isAllowed( $right ) ) {
2163 $errors[] = [ 'protectedpagetext', $right, $action ];
2164 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2165 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2173 * Check restrictions on cascading pages.
2175 * @param string $action The action to check
2176 * @param User $user User to check
2177 * @param array $errors List of current errors
2178 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2179 * @param bool $short Short circuit on first error
2181 * @return array List of errors
2183 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2184 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2185 # We /could/ use the protection level on the source page, but it's
2186 # fairly ugly as we have to establish a precedence hierarchy for pages
2187 # included by multiple cascade-protected pages. So just restrict
2188 # it to people with 'protect' permission, as they could remove the
2189 # protection anyway.
2190 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2191 # Cascading protection depends on more than this page...
2192 # Several cascading protected pages may include this page...
2193 # Check each cascading level
2194 # This is only for protection restrictions, not for all actions
2195 if ( isset( $restrictions[$action] ) ) {
2196 foreach ( $restrictions[$action] as $right ) {
2197 // Backwards compatibility, rewrite sysop -> editprotected
2198 if ( $right == 'sysop' ) {
2199 $right = 'editprotected';
2201 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2202 if ( $right == 'autoconfirmed' ) {
2203 $right = 'editsemiprotected';
2205 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2207 foreach ( $cascadingSources as $page ) {
2208 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2210 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2220 * Check action permissions not already checked in checkQuickPermissions
2222 * @param string $action The action to check
2223 * @param User $user User to check
2224 * @param array $errors List of current errors
2225 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2226 * @param bool $short Short circuit on first error
2228 * @return array List of errors
2230 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2231 global $wgDeleteRevisionsLimit, $wgLang;
2233 if ( $action == 'protect' ) {
2234 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2235 // If they can't edit, they shouldn't protect.
2236 $errors[] = [ 'protect-cantedit' ];
2238 } elseif ( $action == 'create' ) {
2239 $title_protection = $this->getTitleProtection();
2240 if ( $title_protection ) {
2241 if ( $title_protection['permission'] == ''
2242 ||
!$user->isAllowed( $title_protection['permission'] )
2246 User
::whoIs( $title_protection['user'] ),
2247 $title_protection['reason']
2251 } elseif ( $action == 'move' ) {
2252 // Check for immobile pages
2253 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2254 // Specific message for this case
2255 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2256 } elseif ( !$this->isMovable() ) {
2257 // Less specific message for rarer cases
2258 $errors[] = [ 'immobile-source-page' ];
2260 } elseif ( $action == 'move-target' ) {
2261 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2262 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2263 } elseif ( !$this->isMovable() ) {
2264 $errors[] = [ 'immobile-target-page' ];
2266 } elseif ( $action == 'delete' ) {
2267 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2268 if ( !$tempErrors ) {
2269 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2270 $user, $tempErrors, $rigor, true );
2272 if ( $tempErrors ) {
2273 // If protection keeps them from editing, they shouldn't be able to delete.
2274 $errors[] = [ 'deleteprotected' ];
2276 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2277 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2279 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2286 * Check that the user isn't blocked from editing.
2288 * @param string $action The action to check
2289 * @param User $user User to check
2290 * @param array $errors List of current errors
2291 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2292 * @param bool $short Short circuit on first error
2294 * @return array List of errors
2296 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2297 // Account creation blocks handled at userlogin.
2298 // Unblocking handled in SpecialUnblock
2299 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2303 global $wgEmailConfirmToEdit;
2305 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2306 $errors[] = [ 'confirmedittext' ];
2309 $useSlave = ( $rigor !== 'secure' );
2310 if ( ( $action == 'edit' ||
$action == 'create' )
2311 && !$user->isBlockedFrom( $this, $useSlave )
2313 // Don't block the user from editing their own talk page unless they've been
2314 // explicitly blocked from that too.
2315 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2316 // @todo FIXME: Pass the relevant context into this function.
2317 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2324 * Check that the user is allowed to read this page.
2326 * @param string $action The action to check
2327 * @param User $user User to check
2328 * @param array $errors List of current errors
2329 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2330 * @param bool $short Short circuit on first error
2332 * @return array List of errors
2334 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2335 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2337 $whitelisted = false;
2338 if ( User
::isEveryoneAllowed( 'read' ) ) {
2339 # Shortcut for public wikis, allows skipping quite a bit of code
2340 $whitelisted = true;
2341 } elseif ( $user->isAllowed( 'read' ) ) {
2342 # If the user is allowed to read pages, he is allowed to read all pages
2343 $whitelisted = true;
2344 } elseif ( $this->isSpecial( 'Userlogin' )
2345 ||
$this->isSpecial( 'ChangePassword' )
2346 ||
$this->isSpecial( 'PasswordReset' )
2348 # Always grant access to the login page.
2349 # Even anons need to be able to log in.
2350 $whitelisted = true;
2351 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2352 # Time to check the whitelist
2353 # Only do these checks is there's something to check against
2354 $name = $this->getPrefixedText();
2355 $dbName = $this->getPrefixedDBkey();
2357 // Check for explicit whitelisting with and without underscores
2358 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2359 $whitelisted = true;
2360 } elseif ( $this->getNamespace() == NS_MAIN
) {
2361 # Old settings might have the title prefixed with
2362 # a colon for main-namespace pages
2363 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2364 $whitelisted = true;
2366 } elseif ( $this->isSpecialPage() ) {
2367 # If it's a special page, ditch the subpage bit and check again
2368 $name = $this->getDBkey();
2369 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2371 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2372 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2373 $whitelisted = true;
2379 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2380 $name = $this->getPrefixedText();
2381 // Check for regex whitelisting
2382 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2383 if ( preg_match( $listItem, $name ) ) {
2384 $whitelisted = true;
2390 if ( !$whitelisted ) {
2391 # If the title is not whitelisted, give extensions a chance to do so...
2392 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2393 if ( !$whitelisted ) {
2394 $errors[] = $this->missingPermissionError( $action, $short );
2402 * Get a description array when the user doesn't have the right to perform
2403 * $action (i.e. when User::isAllowed() returns false)
2405 * @param string $action The action to check
2406 * @param bool $short Short circuit on first error
2407 * @return array List of errors
2409 private function missingPermissionError( $action, $short ) {
2410 // We avoid expensive display logic for quickUserCan's and such
2412 return [ 'badaccess-group0' ];
2415 $groups = array_map( [ 'User', 'makeGroupLinkWiki' ],
2416 User
::getGroupsWithPermission( $action ) );
2418 if ( count( $groups ) ) {
2422 $wgLang->commaList( $groups ),
2426 return [ 'badaccess-group0' ];
2431 * Can $user perform $action on this page? This is an internal function,
2432 * with multiple levels of checks depending on performance needs; see $rigor below.
2433 * It does not check wfReadOnly().
2435 * @param string $action Action that permission needs to be checked for
2436 * @param User $user User to check
2437 * @param string $rigor One of (quick,full,secure)
2438 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2439 * - full : does cheap and expensive checks possibly from a slave
2440 * - secure : does cheap and expensive checks, using the master as needed
2441 * @param bool $short Set this to true to stop after the first permission error.
2442 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2444 protected function getUserPermissionsErrorsInternal(
2445 $action, $user, $rigor = 'secure', $short = false
2447 if ( $rigor === true ) {
2448 $rigor = 'secure'; // b/c
2449 } elseif ( $rigor === false ) {
2450 $rigor = 'quick'; // b/c
2451 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2452 throw new Exception( "Invalid rigor parameter '$rigor'." );
2455 # Read has special handling
2456 if ( $action == 'read' ) {
2458 'checkPermissionHooks',
2459 'checkReadPermissions',
2461 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2462 # here as it will lead to duplicate error messages. This is okay to do
2463 # since anywhere that checks for create will also check for edit, and
2464 # those checks are called for edit.
2465 } elseif ( $action == 'create' ) {
2467 'checkQuickPermissions',
2468 'checkPermissionHooks',
2469 'checkPageRestrictions',
2470 'checkCascadingSourcesRestrictions',
2471 'checkActionPermissions',
2476 'checkQuickPermissions',
2477 'checkPermissionHooks',
2478 'checkSpecialsAndNSPermissions',
2479 'checkCSSandJSPermissions',
2480 'checkPageRestrictions',
2481 'checkCascadingSourcesRestrictions',
2482 'checkActionPermissions',
2488 while ( count( $checks ) > 0 &&
2489 !( $short && count( $errors ) > 0 ) ) {
2490 $method = array_shift( $checks );
2491 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2498 * Get a filtered list of all restriction types supported by this wiki.
2499 * @param bool $exists True to get all restriction types that apply to
2500 * titles that do exist, False for all restriction types that apply to
2501 * titles that do not exist
2504 public static function getFilteredRestrictionTypes( $exists = true ) {
2505 global $wgRestrictionTypes;
2506 $types = $wgRestrictionTypes;
2508 # Remove the create restriction for existing titles
2509 $types = array_diff( $types, [ 'create' ] );
2511 # Only the create and upload restrictions apply to non-existing titles
2512 $types = array_intersect( $types, [ 'create', 'upload' ] );
2518 * Returns restriction types for the current Title
2520 * @return array Applicable restriction types
2522 public function getRestrictionTypes() {
2523 if ( $this->isSpecialPage() ) {
2527 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2529 if ( $this->getNamespace() != NS_FILE
) {
2530 # Remove the upload restriction for non-file titles
2531 $types = array_diff( $types, [ 'upload' ] );
2534 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2536 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2537 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2543 * Is this title subject to title protection?
2544 * Title protection is the one applied against creation of such title.
2546 * @return array|bool An associative array representing any existent title
2547 * protection, or false if there's none.
2549 public function getTitleProtection() {
2550 // Can't protect pages in special namespaces
2551 if ( $this->getNamespace() < 0 ) {
2555 // Can't protect pages that exist.
2556 if ( $this->exists() ) {
2560 if ( $this->mTitleProtection
=== null ) {
2561 $dbr = wfGetDB( DB_SLAVE
);
2562 $res = $dbr->select(
2565 'user' => 'pt_user',
2566 'reason' => 'pt_reason',
2567 'expiry' => 'pt_expiry',
2568 'permission' => 'pt_create_perm'
2570 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2574 // fetchRow returns false if there are no rows.
2575 $row = $dbr->fetchRow( $res );
2577 if ( $row['permission'] == 'sysop' ) {
2578 $row['permission'] = 'editprotected'; // B/C
2580 if ( $row['permission'] == 'autoconfirmed' ) {
2581 $row['permission'] = 'editsemiprotected'; // B/C
2583 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2585 $this->mTitleProtection
= $row;
2587 return $this->mTitleProtection
;
2591 * Remove any title protection due to page existing
2593 public function deleteTitleProtection() {
2594 $dbw = wfGetDB( DB_MASTER
);
2598 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2601 $this->mTitleProtection
= false;
2605 * Is this page "semi-protected" - the *only* protection levels are listed
2606 * in $wgSemiprotectedRestrictionLevels?
2608 * @param string $action Action to check (default: edit)
2611 public function isSemiProtected( $action = 'edit' ) {
2612 global $wgSemiprotectedRestrictionLevels;
2614 $restrictions = $this->getRestrictions( $action );
2615 $semi = $wgSemiprotectedRestrictionLevels;
2616 if ( !$restrictions ||
!$semi ) {
2617 // Not protected, or all protection is full protection
2621 // Remap autoconfirmed to editsemiprotected for BC
2622 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2623 $semi[$key] = 'editsemiprotected';
2625 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2626 $restrictions[$key] = 'editsemiprotected';
2629 return !array_diff( $restrictions, $semi );
2633 * Does the title correspond to a protected article?
2635 * @param string $action The action the page is protected from,
2636 * by default checks all actions.
2639 public function isProtected( $action = '' ) {
2640 global $wgRestrictionLevels;
2642 $restrictionTypes = $this->getRestrictionTypes();
2644 # Special pages have inherent protection
2645 if ( $this->isSpecialPage() ) {
2649 # Check regular protection levels
2650 foreach ( $restrictionTypes as $type ) {
2651 if ( $action == $type ||
$action == '' ) {
2652 $r = $this->getRestrictions( $type );
2653 foreach ( $wgRestrictionLevels as $level ) {
2654 if ( in_array( $level, $r ) && $level != '' ) {
2665 * Determines if $user is unable to edit this page because it has been protected
2666 * by $wgNamespaceProtection.
2668 * @param User $user User object to check permissions
2671 public function isNamespaceProtected( User
$user ) {
2672 global $wgNamespaceProtection;
2674 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2675 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2676 if ( $right != '' && !$user->isAllowed( $right ) ) {
2685 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2687 * @return bool If the page is subject to cascading restrictions.
2689 public function isCascadeProtected() {
2690 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2691 return ( $sources > 0 );
2695 * Determines whether cascading protection sources have already been loaded from
2698 * @param bool $getPages True to check if the pages are loaded, or false to check
2699 * if the status is loaded.
2700 * @return bool Whether or not the specified information has been loaded
2703 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2704 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2708 * Cascading protection: Get the source of any cascading restrictions on this page.
2710 * @param bool $getPages Whether or not to retrieve the actual pages
2711 * that the restrictions have come from and the actual restrictions
2713 * @return array Two elements: First is an array of Title objects of the
2714 * pages from which cascading restrictions have come, false for
2715 * none, or true if such restrictions exist but $getPages was not
2716 * set. Second is an array like that returned by
2717 * Title::getAllRestrictions(), or an empty array if $getPages is
2720 public function getCascadeProtectionSources( $getPages = true ) {
2721 $pagerestrictions = [];
2723 if ( $this->mCascadeSources
!== null && $getPages ) {
2724 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2725 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2726 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2729 $dbr = wfGetDB( DB_SLAVE
);
2731 if ( $this->getNamespace() == NS_FILE
) {
2732 $tables = [ 'imagelinks', 'page_restrictions' ];
2734 'il_to' => $this->getDBkey(),
2739 $tables = [ 'templatelinks', 'page_restrictions' ];
2741 'tl_namespace' => $this->getNamespace(),
2742 'tl_title' => $this->getDBkey(),
2749 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2750 'pr_expiry', 'pr_type', 'pr_level' ];
2751 $where_clauses[] = 'page_id=pr_page';
2754 $cols = [ 'pr_expiry' ];
2757 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2759 $sources = $getPages ?
[] : false;
2760 $now = wfTimestampNow();
2762 foreach ( $res as $row ) {
2763 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2764 if ( $expiry > $now ) {
2766 $page_id = $row->pr_page
;
2767 $page_ns = $row->page_namespace
;
2768 $page_title = $row->page_title
;
2769 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2770 # Add groups needed for each restriction type if its not already there
2771 # Make sure this restriction type still exists
2773 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2774 $pagerestrictions[$row->pr_type
] = [];
2778 isset( $pagerestrictions[$row->pr_type
] )
2779 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2781 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2790 $this->mCascadeSources
= $sources;
2791 $this->mCascadingRestrictions
= $pagerestrictions;
2793 $this->mHasCascadingRestrictions
= $sources;
2796 return [ $sources, $pagerestrictions ];
2800 * Accessor for mRestrictionsLoaded
2802 * @return bool Whether or not the page's restrictions have already been
2803 * loaded from the database
2806 public function areRestrictionsLoaded() {
2807 return $this->mRestrictionsLoaded
;
2811 * Accessor/initialisation for mRestrictions
2813 * @param string $action Action that permission needs to be checked for
2814 * @return array Restriction levels needed to take the action. All levels are
2815 * required. Note that restriction levels are normally user rights, but 'sysop'
2816 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2817 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2819 public function getRestrictions( $action ) {
2820 if ( !$this->mRestrictionsLoaded
) {
2821 $this->loadRestrictions();
2823 return isset( $this->mRestrictions
[$action] )
2824 ?
$this->mRestrictions
[$action]
2829 * Accessor/initialisation for mRestrictions
2831 * @return array Keys are actions, values are arrays as returned by
2832 * Title::getRestrictions()
2835 public function getAllRestrictions() {
2836 if ( !$this->mRestrictionsLoaded
) {
2837 $this->loadRestrictions();
2839 return $this->mRestrictions
;
2843 * Get the expiry time for the restriction against a given action
2845 * @param string $action
2846 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2847 * or not protected at all, or false if the action is not recognised.
2849 public function getRestrictionExpiry( $action ) {
2850 if ( !$this->mRestrictionsLoaded
) {
2851 $this->loadRestrictions();
2853 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2857 * Returns cascading restrictions for the current article
2861 function areRestrictionsCascading() {
2862 if ( !$this->mRestrictionsLoaded
) {
2863 $this->loadRestrictions();
2866 return $this->mCascadeRestriction
;
2870 * Loads a string into mRestrictions array
2872 * @param ResultWrapper $res Resource restrictions as an SQL result.
2873 * @param string $oldFashionedRestrictions Comma-separated list of page
2874 * restrictions from page table (pre 1.10)
2876 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2879 foreach ( $res as $row ) {
2883 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2887 * Compiles list of active page restrictions from both page table (pre 1.10)
2888 * and page_restrictions table for this existing page.
2889 * Public for usage by LiquidThreads.
2891 * @param array $rows Array of db result objects
2892 * @param string $oldFashionedRestrictions Comma-separated list of page
2893 * restrictions from page table (pre 1.10)
2895 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2896 $dbr = wfGetDB( DB_SLAVE
);
2898 $restrictionTypes = $this->getRestrictionTypes();
2900 foreach ( $restrictionTypes as $type ) {
2901 $this->mRestrictions
[$type] = [];
2902 $this->mRestrictionsExpiry
[$type] = 'infinity';
2905 $this->mCascadeRestriction
= false;
2907 # Backwards-compatibility: also load the restrictions from the page record (old format).
2908 if ( $oldFashionedRestrictions !== null ) {
2909 $this->mOldRestrictions
= $oldFashionedRestrictions;
2912 if ( $this->mOldRestrictions
=== false ) {
2913 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2914 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
2917 if ( $this->mOldRestrictions
!= '' ) {
2918 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2919 $temp = explode( '=', trim( $restrict ) );
2920 if ( count( $temp ) == 1 ) {
2921 // old old format should be treated as edit/move restriction
2922 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2923 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2925 $restriction = trim( $temp[1] );
2926 if ( $restriction != '' ) { // some old entries are empty
2927 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2933 if ( count( $rows ) ) {
2934 # Current system - load second to make them override.
2935 $now = wfTimestampNow();
2937 # Cycle through all the restrictions.
2938 foreach ( $rows as $row ) {
2940 // Don't take care of restrictions types that aren't allowed
2941 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2945 // This code should be refactored, now that it's being used more generally,
2946 // But I don't really see any harm in leaving it in Block for now -werdna
2947 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2949 // Only apply the restrictions if they haven't expired!
2950 if ( !$expiry ||
$expiry > $now ) {
2951 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2952 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2954 $this->mCascadeRestriction |
= $row->pr_cascade
;
2959 $this->mRestrictionsLoaded
= true;
2963 * Load restrictions from the page_restrictions table
2965 * @param string $oldFashionedRestrictions Comma-separated list of page
2966 * restrictions from page table (pre 1.10)
2968 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2969 if ( !$this->mRestrictionsLoaded
) {
2970 $dbr = wfGetDB( DB_SLAVE
);
2971 if ( $this->exists() ) {
2972 $res = $dbr->select(
2973 'page_restrictions',
2974 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2975 [ 'pr_page' => $this->getArticleID() ],
2979 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2981 $title_protection = $this->getTitleProtection();
2983 if ( $title_protection ) {
2984 $now = wfTimestampNow();
2985 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
2987 if ( !$expiry ||
$expiry > $now ) {
2988 // Apply the restrictions
2989 $this->mRestrictionsExpiry
['create'] = $expiry;
2990 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
2991 } else { // Get rid of the old restrictions
2992 $this->mTitleProtection
= false;
2995 $this->mRestrictionsExpiry
['create'] = 'infinity';
2997 $this->mRestrictionsLoaded
= true;
3003 * Flush the protection cache in this object and force reload from the database.
3004 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3006 public function flushRestrictions() {
3007 $this->mRestrictionsLoaded
= false;
3008 $this->mTitleProtection
= null;
3012 * Purge expired restrictions from the page_restrictions table
3014 static function purgeExpiredRestrictions() {
3015 if ( wfReadOnly() ) {
3019 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3020 wfGetDB( DB_MASTER
),
3022 function ( IDatabase
$dbw, $fname ) {
3024 'page_restrictions',
3025 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3030 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3038 * Does this have subpages? (Warning, usually requires an extra DB query.)
3042 public function hasSubpages() {
3043 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3048 # We dynamically add a member variable for the purpose of this method
3049 # alone to cache the result. There's no point in having it hanging
3050 # around uninitialized in every Title object; therefore we only add it
3051 # if needed and don't declare it statically.
3052 if ( $this->mHasSubpages
=== null ) {
3053 $this->mHasSubpages
= false;
3054 $subpages = $this->getSubpages( 1 );
3055 if ( $subpages instanceof TitleArray
) {
3056 $this->mHasSubpages
= (bool)$subpages->count();
3060 return $this->mHasSubpages
;
3064 * Get all subpages of this page.
3066 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3067 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3068 * doesn't allow subpages
3070 public function getSubpages( $limit = -1 ) {
3071 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3075 $dbr = wfGetDB( DB_SLAVE
);
3076 $conds['page_namespace'] = $this->getNamespace();
3077 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3079 if ( $limit > -1 ) {
3080 $options['LIMIT'] = $limit;
3082 $this->mSubpages
= TitleArray
::newFromResult(
3083 $dbr->select( 'page',
3084 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3090 return $this->mSubpages
;
3094 * Is there a version of this page in the deletion archive?
3096 * @return int The number of archived revisions
3098 public function isDeleted() {
3099 if ( $this->getNamespace() < 0 ) {
3102 $dbr = wfGetDB( DB_SLAVE
);
3104 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3105 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3108 if ( $this->getNamespace() == NS_FILE
) {
3109 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3110 [ 'fa_name' => $this->getDBkey() ],
3119 * Is there a version of this page in the deletion archive?
3123 public function isDeletedQuick() {
3124 if ( $this->getNamespace() < 0 ) {
3127 $dbr = wfGetDB( DB_SLAVE
);
3128 $deleted = (bool)$dbr->selectField( 'archive', '1',
3129 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3132 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3133 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3134 [ 'fa_name' => $this->getDBkey() ],
3142 * Get the article ID for this Title from the link cache,
3143 * adding it if necessary
3145 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3147 * @return int The ID
3149 public function getArticleID( $flags = 0 ) {
3150 if ( $this->getNamespace() < 0 ) {
3151 $this->mArticleID
= 0;
3152 return $this->mArticleID
;
3154 $linkCache = LinkCache
::singleton();
3155 if ( $flags & self
::GAID_FOR_UPDATE
) {
3156 $oldUpdate = $linkCache->forUpdate( true );
3157 $linkCache->clearLink( $this );
3158 $this->mArticleID
= $linkCache->addLinkObj( $this );
3159 $linkCache->forUpdate( $oldUpdate );
3161 if ( -1 == $this->mArticleID
) {
3162 $this->mArticleID
= $linkCache->addLinkObj( $this );
3165 return $this->mArticleID
;
3169 * Is this an article that is a redirect page?
3170 * Uses link cache, adding it if necessary
3172 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3175 public function isRedirect( $flags = 0 ) {
3176 if ( !is_null( $this->mRedirect
) ) {
3177 return $this->mRedirect
;
3179 if ( !$this->getArticleID( $flags ) ) {
3180 $this->mRedirect
= false;
3181 return $this->mRedirect
;
3184 $linkCache = LinkCache
::singleton();
3185 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3186 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3187 if ( $cached === null ) {
3188 # Trust LinkCache's state over our own
3189 # LinkCache is telling us that the page doesn't exist, despite there being cached
3190 # data relating to an existing page in $this->mArticleID. Updaters should clear
3191 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3192 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3193 # LinkCache to refresh its data from the master.
3194 $this->mRedirect
= false;
3195 return $this->mRedirect
;
3198 $this->mRedirect
= (bool)$cached;
3200 return $this->mRedirect
;
3204 * What is the length of this page?
3205 * Uses link cache, adding it if necessary
3207 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3210 public function getLength( $flags = 0 ) {
3211 if ( $this->mLength
!= -1 ) {
3212 return $this->mLength
;
3214 if ( !$this->getArticleID( $flags ) ) {
3216 return $this->mLength
;
3218 $linkCache = LinkCache
::singleton();
3219 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3220 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3221 if ( $cached === null ) {
3222 # Trust LinkCache's state over our own, as for isRedirect()
3224 return $this->mLength
;
3227 $this->mLength
= intval( $cached );
3229 return $this->mLength
;
3233 * What is the page_latest field for this page?
3235 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3236 * @return int Int or 0 if the page doesn't exist
3238 public function getLatestRevID( $flags = 0 ) {
3239 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3240 return intval( $this->mLatestID
);
3242 if ( !$this->getArticleID( $flags ) ) {
3243 $this->mLatestID
= 0;
3244 return $this->mLatestID
;
3246 $linkCache = LinkCache
::singleton();
3247 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3248 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3249 if ( $cached === null ) {
3250 # Trust LinkCache's state over our own, as for isRedirect()
3251 $this->mLatestID
= 0;
3252 return $this->mLatestID
;
3255 $this->mLatestID
= intval( $cached );
3257 return $this->mLatestID
;
3261 * This clears some fields in this object, and clears any associated
3262 * keys in the "bad links" section of the link cache.
3264 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3265 * loading of the new page_id. It's also called from
3266 * WikiPage::doDeleteArticleReal()
3268 * @param int $newid The new Article ID
3270 public function resetArticleID( $newid ) {
3271 $linkCache = LinkCache
::singleton();
3272 $linkCache->clearLink( $this );
3274 if ( $newid === false ) {
3275 $this->mArticleID
= -1;
3277 $this->mArticleID
= intval( $newid );
3279 $this->mRestrictionsLoaded
= false;
3280 $this->mRestrictions
= [];
3281 $this->mOldRestrictions
= false;
3282 $this->mRedirect
= null;
3283 $this->mLength
= -1;
3284 $this->mLatestID
= false;
3285 $this->mContentModel
= false;
3286 $this->mEstimateRevisions
= null;
3287 $this->mPageLanguage
= false;
3288 $this->mDbPageLanguage
= false;
3289 $this->mIsBigDeletion
= null;
3292 public static function clearCaches() {
3293 $linkCache = LinkCache
::singleton();
3294 $linkCache->clear();
3296 $titleCache = self
::getTitleCache();
3297 $titleCache->clear();
3301 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3303 * @param string $text Containing title to capitalize
3304 * @param int $ns Namespace index, defaults to NS_MAIN
3305 * @return string Containing capitalized title
3307 public static function capitalize( $text, $ns = NS_MAIN
) {
3310 if ( MWNamespace
::isCapitalized( $ns ) ) {
3311 return $wgContLang->ucfirst( $text );
3318 * Secure and split - main initialisation function for this object
3320 * Assumes that mDbkeyform has been set, and is urldecoded
3321 * and uses underscores, but not otherwise munged. This function
3322 * removes illegal characters, splits off the interwiki and
3323 * namespace prefixes, sets the other forms, and canonicalizes
3326 * @throws MalformedTitleException On invalid titles
3327 * @return bool True on success
3329 private function secureAndSplit() {
3331 $this->mInterwiki
= '';
3332 $this->mFragment
= '';
3333 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3335 $dbkey = $this->mDbkeyform
;
3337 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3338 // the parsing code with Title, while avoiding massive refactoring.
3339 // @todo: get rid of secureAndSplit, refactor parsing code.
3340 $titleParser = self
::getMediaWikiTitleCodec();
3341 // MalformedTitleException can be thrown here
3342 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3345 $this->setFragment( '#' . $parts['fragment'] );
3346 $this->mInterwiki
= $parts['interwiki'];
3347 $this->mLocalInterwiki
= $parts['local_interwiki'];
3348 $this->mNamespace
= $parts['namespace'];
3349 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3351 $this->mDbkeyform
= $parts['dbkey'];
3352 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3353 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3355 # We already know that some pages won't be in the database!
3356 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3357 $this->mArticleID
= 0;
3364 * Get an array of Title objects linking to this Title
3365 * Also stores the IDs in the link cache.
3367 * WARNING: do not use this function on arbitrary user-supplied titles!
3368 * On heavily-used templates it will max out the memory.
3370 * @param array $options May be FOR UPDATE
3371 * @param string $table Table name
3372 * @param string $prefix Fields prefix
3373 * @return Title[] Array of Title objects linking here
3375 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3376 if ( count( $options ) > 0 ) {
3377 $db = wfGetDB( DB_MASTER
);
3379 $db = wfGetDB( DB_SLAVE
);
3384 self
::getSelectFields(),
3386 "{$prefix}_from=page_id",
3387 "{$prefix}_namespace" => $this->getNamespace(),
3388 "{$prefix}_title" => $this->getDBkey() ],
3394 if ( $res->numRows() ) {
3395 $linkCache = LinkCache
::singleton();
3396 foreach ( $res as $row ) {
3397 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3399 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3400 $retVal[] = $titleObj;
3408 * Get an array of Title objects using this Title as a template
3409 * Also stores the IDs in the link cache.
3411 * WARNING: do not use this function on arbitrary user-supplied titles!
3412 * On heavily-used templates it will max out the memory.
3414 * @param array $options Query option to Database::select()
3415 * @return Title[] Array of Title the Title objects linking here
3417 public function getTemplateLinksTo( $options = [] ) {
3418 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3422 * Get an array of Title objects linked from this Title
3423 * Also stores the IDs in the link cache.
3425 * WARNING: do not use this function on arbitrary user-supplied titles!
3426 * On heavily-used templates it will max out the memory.
3428 * @param array $options Query option to Database::select()
3429 * @param string $table Table name
3430 * @param string $prefix Fields prefix
3431 * @return array Array of Title objects linking here
3433 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3434 $id = $this->getArticleID();
3436 # If the page doesn't exist; there can't be any link from this page
3441 $db = wfGetDB( DB_SLAVE
);
3443 $blNamespace = "{$prefix}_namespace";
3444 $blTitle = "{$prefix}_title";
3449 [ $blNamespace, $blTitle ],
3450 WikiPage
::selectFields()
3452 [ "{$prefix}_from" => $id ],
3457 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3462 $linkCache = LinkCache
::singleton();
3463 foreach ( $res as $row ) {
3464 if ( $row->page_id
) {
3465 $titleObj = Title
::newFromRow( $row );
3467 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3468 $linkCache->addBadLinkObj( $titleObj );
3470 $retVal[] = $titleObj;
3477 * Get an array of Title objects used on this Title as a template
3478 * Also stores the IDs in the link cache.
3480 * WARNING: do not use this function on arbitrary user-supplied titles!
3481 * On heavily-used templates it will max out the memory.
3483 * @param array $options May be FOR UPDATE
3484 * @return Title[] Array of Title the Title objects used here
3486 public function getTemplateLinksFrom( $options = [] ) {
3487 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3491 * Get an array of Title objects referring to non-existent articles linked
3494 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3495 * should use redirect table in this case).
3496 * @return Title[] Array of Title the Title objects
3498 public function getBrokenLinksFrom() {
3499 if ( $this->getArticleID() == 0 ) {
3500 # All links from article ID 0 are false positives
3504 $dbr = wfGetDB( DB_SLAVE
);
3505 $res = $dbr->select(
3506 [ 'page', 'pagelinks' ],
3507 [ 'pl_namespace', 'pl_title' ],
3509 'pl_from' => $this->getArticleID(),
3510 'page_namespace IS NULL'
3516 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3522 foreach ( $res as $row ) {
3523 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3529 * Get a list of URLs to purge from the CDN cache when this
3532 * @return string[] Array of String the URLs
3534 public function getCdnUrls() {
3536 $this->getInternalURL(),
3537 $this->getInternalURL( 'action=history' )
3540 $pageLang = $this->getPageLanguage();
3541 if ( $pageLang->hasVariants() ) {
3542 $variants = $pageLang->getVariants();
3543 foreach ( $variants as $vCode ) {
3544 $urls[] = $this->getInternalURL( $vCode );
3548 // If we are looking at a css/js user subpage, purge the action=raw.
3549 if ( $this->isJsSubpage() ) {
3550 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3551 } elseif ( $this->isCssSubpage() ) {
3552 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3555 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3560 * @deprecated since 1.27 use getCdnUrls()
3562 public function getSquidURLs() {
3563 return $this->getCdnUrls();
3567 * Purge all applicable CDN URLs
3569 public function purgeSquid() {
3570 DeferredUpdates
::addUpdate(
3571 new CdnCacheUpdate( $this->getCdnUrls() ),
3572 DeferredUpdates
::PRESEND
3577 * Move this page without authentication
3579 * @deprecated since 1.25 use MovePage class instead
3580 * @param Title $nt The new page Title
3581 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3583 public function moveNoAuth( &$nt ) {
3584 wfDeprecated( __METHOD__
, '1.25' );
3585 return $this->moveTo( $nt, false );
3589 * Check whether a given move operation would be valid.
3590 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3592 * @deprecated since 1.25, use MovePage's methods instead
3593 * @param Title $nt The new title
3594 * @param bool $auth Whether to check user permissions (uses $wgUser)
3595 * @param string $reason Is the log summary of the move, used for spam checking
3596 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3598 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3601 if ( !( $nt instanceof Title
) ) {
3602 // Normally we'd add this to $errors, but we'll get
3603 // lots of syntax errors if $nt is not an object
3604 return [ [ 'badtitletext' ] ];
3607 $mp = new MovePage( $this, $nt );
3608 $errors = $mp->isValidMove()->getErrorsArray();
3610 $errors = wfMergeErrorArrays(
3612 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3616 return $errors ?
: true;
3620 * Check if the requested move target is a valid file move target
3621 * @todo move this to MovePage
3622 * @param Title $nt Target title
3623 * @return array List of errors
3625 protected function validateFileMoveOperation( $nt ) {
3630 $destFile = wfLocalFile( $nt );
3631 $destFile->load( File
::READ_LATEST
);
3632 if ( !$wgUser->isAllowed( 'reupload-shared' )
3633 && !$destFile->exists() && wfFindFile( $nt )
3635 $errors[] = [ 'file-exists-sharedrepo' ];
3642 * Move a title to a new location
3644 * @deprecated since 1.25, use the MovePage class instead
3645 * @param Title $nt The new title
3646 * @param bool $auth Indicates whether $wgUser's permissions
3648 * @param string $reason The reason for the move
3649 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3650 * Ignored if the user doesn't have the suppressredirect right.
3651 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3653 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3655 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3656 if ( is_array( $err ) ) {
3657 // Auto-block user's IP if the account was "hard" blocked
3658 $wgUser->spreadAnyEditBlock();
3661 // Check suppressredirect permission
3662 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3663 $createRedirect = true;
3666 $mp = new MovePage( $this, $nt );
3667 $status = $mp->move( $wgUser, $reason, $createRedirect );
3668 if ( $status->isOK() ) {
3671 return $status->getErrorsArray();
3676 * Move this page's subpages to be subpages of $nt
3678 * @param Title $nt Move target
3679 * @param bool $auth Whether $wgUser's permissions should be checked
3680 * @param string $reason The reason for the move
3681 * @param bool $createRedirect Whether to create redirects from the old subpages to
3682 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3683 * @return array Array with old page titles as keys, and strings (new page titles) or
3684 * arrays (errors) as values, or an error array with numeric indices if no pages
3687 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3688 global $wgMaximumMovedPages;
3689 // Check permissions
3690 if ( !$this->userCan( 'move-subpages' ) ) {
3691 return [ 'cant-move-subpages' ];
3693 // Do the source and target namespaces support subpages?
3694 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3695 return [ 'namespace-nosubpages',
3696 MWNamespace
::getCanonicalName( $this->getNamespace() ) ];
3698 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3699 return [ 'namespace-nosubpages',
3700 MWNamespace
::getCanonicalName( $nt->getNamespace() ) ];
3703 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3706 foreach ( $subpages as $oldSubpage ) {
3708 if ( $count > $wgMaximumMovedPages ) {
3709 $retval[$oldSubpage->getPrefixedText()] =
3710 [ 'movepage-max-pages',
3711 $wgMaximumMovedPages ];
3715 // We don't know whether this function was called before
3716 // or after moving the root page, so check both
3718 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3719 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3721 // When moving a page to a subpage of itself,
3722 // don't move it twice
3725 $newPageName = preg_replace(
3726 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3727 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3728 $oldSubpage->getDBkey() );
3729 if ( $oldSubpage->isTalkPage() ) {
3730 $newNs = $nt->getTalkPage()->getNamespace();
3732 $newNs = $nt->getSubjectPage()->getNamespace();
3734 # Bug 14385: we need makeTitleSafe because the new page names may
3735 # be longer than 255 characters.
3736 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3738 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3739 if ( $success === true ) {
3740 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3742 $retval[$oldSubpage->getPrefixedText()] = $success;
3749 * Checks if this page is just a one-rev redirect.
3750 * Adds lock, so don't use just for light purposes.
3754 public function isSingleRevRedirect() {
3755 global $wgContentHandlerUseDB;
3757 $dbw = wfGetDB( DB_MASTER
);
3760 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3761 if ( $wgContentHandlerUseDB ) {
3762 $fields[] = 'page_content_model';
3765 $row = $dbw->selectRow( 'page',
3771 # Cache some fields we may want
3772 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3773 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3774 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3775 $this->mContentModel
= $row && isset( $row->page_content_model
)
3776 ?
strval( $row->page_content_model
)
3779 if ( !$this->mRedirect
) {
3782 # Does the article have a history?
3783 $row = $dbw->selectField( [ 'page', 'revision' ],
3785 [ 'page_namespace' => $this->getNamespace(),
3786 'page_title' => $this->getDBkey(),
3788 'page_latest != rev_id'
3793 # Return true if there was no history
3794 return ( $row === false );
3798 * Checks if $this can be moved to a given Title
3799 * - Selects for update, so don't call it unless you mean business
3801 * @deprecated since 1.25, use MovePage's methods instead
3802 * @param Title $nt The new title to check
3805 public function isValidMoveTarget( $nt ) {
3806 # Is it an existing file?
3807 if ( $nt->getNamespace() == NS_FILE
) {
3808 $file = wfLocalFile( $nt );
3809 $file->load( File
::READ_LATEST
);
3810 if ( $file->exists() ) {
3811 wfDebug( __METHOD__
. ": file exists\n" );
3815 # Is it a redirect with no history?
3816 if ( !$nt->isSingleRevRedirect() ) {
3817 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3820 # Get the article text
3821 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3822 if ( !is_object( $rev ) ) {
3825 $content = $rev->getContent();
3826 # Does the redirect point to the source?
3827 # Or is it a broken self-redirect, usually caused by namespace collisions?
3828 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3830 if ( $redirTitle ) {
3831 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3832 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3833 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3839 # Fail safe (not a redirect after all. strange.)
3840 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3841 " is a redirect, but it doesn't contain a valid redirect.\n" );
3847 * Get categories to which this Title belongs and return an array of
3848 * categories' names.
3850 * @return array Array of parents in the form:
3851 * $parent => $currentarticle
3853 public function getParentCategories() {
3858 $titleKey = $this->getArticleID();
3860 if ( $titleKey === 0 ) {
3864 $dbr = wfGetDB( DB_SLAVE
);
3866 $res = $dbr->select(
3869 [ 'cl_from' => $titleKey ],
3873 if ( $res->numRows() > 0 ) {
3874 foreach ( $res as $row ) {
3875 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3876 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3883 * Get a tree of parent categories
3885 * @param array $children Array with the children in the keys, to check for circular refs
3886 * @return array Tree of parent categories
3888 public function getParentCategoryTree( $children = [] ) {
3890 $parents = $this->getParentCategories();
3893 foreach ( $parents as $parent => $current ) {
3894 if ( array_key_exists( $parent, $children ) ) {
3895 # Circular reference
3896 $stack[$parent] = [];
3898 $nt = Title
::newFromText( $parent );
3900 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3910 * Get an associative array for selecting this title from
3913 * @return array Array suitable for the $where parameter of DB::select()
3915 public function pageCond() {
3916 if ( $this->mArticleID
> 0 ) {
3917 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3918 return [ 'page_id' => $this->mArticleID
];
3920 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3925 * Get the revision ID of the previous revision
3927 * @param int $revId Revision ID. Get the revision that was before this one.
3928 * @param int $flags Title::GAID_FOR_UPDATE
3929 * @return int|bool Old revision ID, or false if none exists
3931 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3932 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3933 $revId = $db->selectField( 'revision', 'rev_id',
3935 'rev_page' => $this->getArticleID( $flags ),
3936 'rev_id < ' . intval( $revId )
3939 [ 'ORDER BY' => 'rev_id DESC' ]
3942 if ( $revId === false ) {
3945 return intval( $revId );
3950 * Get the revision ID of the next revision
3952 * @param int $revId Revision ID. Get the revision that was after this one.
3953 * @param int $flags Title::GAID_FOR_UPDATE
3954 * @return int|bool Next revision ID, or false if none exists
3956 public function getNextRevisionID( $revId, $flags = 0 ) {
3957 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3958 $revId = $db->selectField( 'revision', 'rev_id',
3960 'rev_page' => $this->getArticleID( $flags ),
3961 'rev_id > ' . intval( $revId )
3964 [ 'ORDER BY' => 'rev_id' ]
3967 if ( $revId === false ) {
3970 return intval( $revId );
3975 * Get the first revision of the page
3977 * @param int $flags Title::GAID_FOR_UPDATE
3978 * @return Revision|null If page doesn't exist
3980 public function getFirstRevision( $flags = 0 ) {
3981 $pageId = $this->getArticleID( $flags );
3983 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3984 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3985 [ 'rev_page' => $pageId ],
3987 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ]
3990 return new Revision( $row );
3997 * Get the oldest revision timestamp of this page
3999 * @param int $flags Title::GAID_FOR_UPDATE
4000 * @return string MW timestamp
4002 public function getEarliestRevTime( $flags = 0 ) {
4003 $rev = $this->getFirstRevision( $flags );
4004 return $rev ?
$rev->getTimestamp() : null;
4008 * Check if this is a new page
4012 public function isNewPage() {
4013 $dbr = wfGetDB( DB_SLAVE
);
4014 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4018 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4022 public function isBigDeletion() {
4023 global $wgDeleteRevisionsLimit;
4025 if ( !$wgDeleteRevisionsLimit ) {
4029 if ( $this->mIsBigDeletion
=== null ) {
4030 $dbr = wfGetDB( DB_SLAVE
);
4032 $revCount = $dbr->selectRowCount(
4035 [ 'rev_page' => $this->getArticleID() ],
4037 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4040 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4043 return $this->mIsBigDeletion
;
4047 * Get the approximate revision count of this page.
4051 public function estimateRevisionCount() {
4052 if ( !$this->exists() ) {
4056 if ( $this->mEstimateRevisions
=== null ) {
4057 $dbr = wfGetDB( DB_SLAVE
);
4058 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4059 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4062 return $this->mEstimateRevisions
;
4066 * Get the number of revisions between the given revision.
4067 * Used for diffs and other things that really need it.
4069 * @param int|Revision $old Old revision or rev ID (first before range)
4070 * @param int|Revision $new New revision or rev ID (first after range)
4071 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4072 * @return int Number of revisions between these revisions.
4074 public function countRevisionsBetween( $old, $new, $max = null ) {
4075 if ( !( $old instanceof Revision
) ) {
4076 $old = Revision
::newFromTitle( $this, (int)$old );
4078 if ( !( $new instanceof Revision
) ) {
4079 $new = Revision
::newFromTitle( $this, (int)$new );
4081 if ( !$old ||
!$new ) {
4082 return 0; // nothing to compare
4084 $dbr = wfGetDB( DB_SLAVE
);
4086 'rev_page' => $this->getArticleID(),
4087 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4088 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4090 if ( $max !== null ) {
4091 return $dbr->selectRowCount( 'revision', '1',
4094 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4097 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4102 * Get the authors between the given revisions or revision IDs.
4103 * Used for diffs and other things that really need it.
4107 * @param int|Revision $old Old revision or rev ID (first before range by default)
4108 * @param int|Revision $new New revision or rev ID (first after range by default)
4109 * @param int $limit Maximum number of authors
4110 * @param string|array $options (Optional): Single option, or an array of options:
4111 * 'include_old' Include $old in the range; $new is excluded.
4112 * 'include_new' Include $new in the range; $old is excluded.
4113 * 'include_both' Include both $old and $new in the range.
4114 * Unknown option values are ignored.
4115 * @return array|null Names of revision authors in the range; null if not both revisions exist
4117 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4118 if ( !( $old instanceof Revision
) ) {
4119 $old = Revision
::newFromTitle( $this, (int)$old );
4121 if ( !( $new instanceof Revision
) ) {
4122 $new = Revision
::newFromTitle( $this, (int)$new );
4124 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4125 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4126 // in the sanity check below?
4127 if ( !$old ||
!$new ) {
4128 return null; // nothing to compare
4133 $options = (array)$options;
4134 if ( in_array( 'include_old', $options ) ) {
4137 if ( in_array( 'include_new', $options ) ) {
4140 if ( in_array( 'include_both', $options ) ) {
4144 // No DB query needed if $old and $new are the same or successive revisions:
4145 if ( $old->getId() === $new->getId() ) {
4146 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4148 [ $old->getUserText( Revision
::RAW
) ];
4149 } elseif ( $old->getId() === $new->getParentId() ) {
4150 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4151 $authors[] = $old->getUserText( Revision
::RAW
);
4152 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4153 $authors[] = $new->getUserText( Revision
::RAW
);
4155 } elseif ( $old_cmp === '>=' ) {
4156 $authors[] = $old->getUserText( Revision
::RAW
);
4157 } elseif ( $new_cmp === '<=' ) {
4158 $authors[] = $new->getUserText( Revision
::RAW
);
4162 $dbr = wfGetDB( DB_SLAVE
);
4163 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4165 'rev_page' => $this->getArticleID(),
4166 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4167 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4169 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4171 foreach ( $res as $row ) {
4172 $authors[] = $row->rev_user_text
;
4178 * Get the number of authors between the given revisions or revision IDs.
4179 * Used for diffs and other things that really need it.
4181 * @param int|Revision $old Old revision or rev ID (first before range by default)
4182 * @param int|Revision $new New revision or rev ID (first after range by default)
4183 * @param int $limit Maximum number of authors
4184 * @param string|array $options (Optional): Single option, or an array of options:
4185 * 'include_old' Include $old in the range; $new is excluded.
4186 * 'include_new' Include $new in the range; $old is excluded.
4187 * 'include_both' Include both $old and $new in the range.
4188 * Unknown option values are ignored.
4189 * @return int Number of revision authors in the range; zero if not both revisions exist
4191 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4192 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4193 return $authors ?
count( $authors ) : 0;
4197 * Compare with another title.
4199 * @param Title $title
4202 public function equals( Title
$title ) {
4203 // Note: === is necessary for proper matching of number-like titles.
4204 return $this->getInterwiki() === $title->getInterwiki()
4205 && $this->getNamespace() == $title->getNamespace()
4206 && $this->getDBkey() === $title->getDBkey();
4210 * Check if this title is a subpage of another title
4212 * @param Title $title
4215 public function isSubpageOf( Title
$title ) {
4216 return $this->getInterwiki() === $title->getInterwiki()
4217 && $this->getNamespace() == $title->getNamespace()
4218 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4222 * Check if page exists. For historical reasons, this function simply
4223 * checks for the existence of the title in the page table, and will
4224 * thus return false for interwiki links, special pages and the like.
4225 * If you want to know if a title can be meaningfully viewed, you should
4226 * probably call the isKnown() method instead.
4228 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4229 * from master/for update
4232 public function exists( $flags = 0 ) {
4233 $exists = $this->getArticleID( $flags ) != 0;
4234 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4239 * Should links to this title be shown as potentially viewable (i.e. as
4240 * "bluelinks"), even if there's no record by this title in the page
4243 * This function is semi-deprecated for public use, as well as somewhat
4244 * misleadingly named. You probably just want to call isKnown(), which
4245 * calls this function internally.
4247 * (ISSUE: Most of these checks are cheap, but the file existence check
4248 * can potentially be quite expensive. Including it here fixes a lot of
4249 * existing code, but we might want to add an optional parameter to skip
4250 * it and any other expensive checks.)
4254 public function isAlwaysKnown() {
4258 * Allows overriding default behavior for determining if a page exists.
4259 * If $isKnown is kept as null, regular checks happen. If it's
4260 * a boolean, this value is returned by the isKnown method.
4264 * @param Title $title
4265 * @param bool|null $isKnown
4267 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4269 if ( !is_null( $isKnown ) ) {
4273 if ( $this->isExternal() ) {
4274 return true; // any interwiki link might be viewable, for all we know
4277 switch ( $this->mNamespace
) {
4280 // file exists, possibly in a foreign repo
4281 return (bool)wfFindFile( $this );
4283 // valid special page
4284 return SpecialPageFactory
::exists( $this->getDBkey() );
4286 // selflink, possibly with fragment
4287 return $this->mDbkeyform
== '';
4289 // known system message
4290 return $this->hasSourceText() !== false;
4297 * Does this title refer to a page that can (or might) be meaningfully
4298 * viewed? In particular, this function may be used to determine if
4299 * links to the title should be rendered as "bluelinks" (as opposed to
4300 * "redlinks" to non-existent pages).
4301 * Adding something else to this function will cause inconsistency
4302 * since LinkHolderArray calls isAlwaysKnown() and does its own
4303 * page existence check.
4307 public function isKnown() {
4308 return $this->isAlwaysKnown() ||
$this->exists();
4312 * Does this page have source text?
4316 public function hasSourceText() {
4317 if ( $this->exists() ) {
4321 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4322 // If the page doesn't exist but is a known system message, default
4323 // message content will be displayed, same for language subpages-
4324 // Use always content language to avoid loading hundreds of languages
4325 // to get the link color.
4327 list( $name, ) = MessageCache
::singleton()->figureMessage(
4328 $wgContLang->lcfirst( $this->getText() )
4330 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4331 return $message->exists();
4338 * Get the default message text or false if the message doesn't exist
4340 * @return string|bool
4342 public function getDefaultMessageText() {
4345 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4349 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4350 $wgContLang->lcfirst( $this->getText() )
4352 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4354 if ( $message->exists() ) {
4355 return $message->plain();
4362 * Updates page_touched for this page; called from LinksUpdate.php
4364 * @param string $purgeTime [optional] TS_MW timestamp
4365 * @return bool True if the update succeeded
4367 public function invalidateCache( $purgeTime = null ) {
4368 if ( wfReadOnly() ) {
4372 if ( $this->mArticleID
=== 0 ) {
4373 return true; // avoid gap locking if we know it's not there
4376 $method = __METHOD__
;
4377 $dbw = wfGetDB( DB_MASTER
);
4378 $conds = $this->pageCond();
4379 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4380 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4384 [ 'page_touched' => $dbTimestamp ],
4385 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4394 * Update page_touched timestamps and send CDN purge messages for
4395 * pages linking to this title. May be sent to the job queue depending
4396 * on the number of links. Typically called on create and delete.
4398 public function touchLinks() {
4399 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4400 if ( $this->getNamespace() == NS_CATEGORY
) {
4401 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4406 * Get the last touched timestamp
4408 * @param IDatabase $db Optional db
4409 * @return string Last-touched timestamp
4411 public function getTouched( $db = null ) {
4412 if ( $db === null ) {
4413 $db = wfGetDB( DB_SLAVE
);
4415 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4420 * Get the timestamp when this page was updated since the user last saw it.
4423 * @return string|null
4425 public function getNotificationTimestamp( $user = null ) {
4428 // Assume current user if none given
4432 // Check cache first
4433 $uid = $user->getId();
4437 // avoid isset here, as it'll return false for null entries
4438 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4439 return $this->mNotificationTimestamp
[$uid];
4441 // Don't cache too much!
4442 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4443 $this->mNotificationTimestamp
= [];
4446 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4447 $watchedItem = $store->getWatchedItem( $user, $this );
4448 if ( $watchedItem ) {
4449 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4451 $this->mNotificationTimestamp
[$uid] = false;
4454 return $this->mNotificationTimestamp
[$uid];
4458 * Generate strings used for xml 'id' names in monobook tabs
4460 * @param string $prepend Defaults to 'nstab-'
4461 * @return string XML 'id' name
4463 public function getNamespaceKey( $prepend = 'nstab-' ) {
4465 // Gets the subject namespace if this title
4466 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4467 // Checks if canonical namespace name exists for namespace
4468 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4469 // Uses canonical namespace name
4470 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4472 // Uses text of namespace
4473 $namespaceKey = $this->getSubjectNsText();
4475 // Makes namespace key lowercase
4476 $namespaceKey = $wgContLang->lc( $namespaceKey );
4478 if ( $namespaceKey == '' ) {
4479 $namespaceKey = 'main';
4481 // Changes file to image for backwards compatibility
4482 if ( $namespaceKey == 'file' ) {
4483 $namespaceKey = 'image';
4485 return $prepend . $namespaceKey;
4489 * Get all extant redirects to this Title
4491 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4492 * @return Title[] Array of Title redirects to this title
4494 public function getRedirectsHere( $ns = null ) {
4497 $dbr = wfGetDB( DB_SLAVE
);
4499 'rd_namespace' => $this->getNamespace(),
4500 'rd_title' => $this->getDBkey(),
4503 if ( $this->isExternal() ) {
4504 $where['rd_interwiki'] = $this->getInterwiki();
4506 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4508 if ( !is_null( $ns ) ) {
4509 $where['page_namespace'] = $ns;
4512 $res = $dbr->select(
4513 [ 'redirect', 'page' ],
4514 [ 'page_namespace', 'page_title' ],
4519 foreach ( $res as $row ) {
4520 $redirs[] = self
::newFromRow( $row );
4526 * Check if this Title is a valid redirect target
4530 public function isValidRedirectTarget() {
4531 global $wgInvalidRedirectTargets;
4533 if ( $this->isSpecialPage() ) {
4534 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4535 if ( $this->isSpecial( 'Userlogout' ) ) {
4539 foreach ( $wgInvalidRedirectTargets as $target ) {
4540 if ( $this->isSpecial( $target ) ) {
4550 * Get a backlink cache object
4552 * @return BacklinkCache
4554 public function getBacklinkCache() {
4555 return BacklinkCache
::get( $this );
4559 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4563 public function canUseNoindex() {
4564 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4566 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4567 ?
$wgContentNamespaces
4568 : $wgExemptFromUserRobotsControl;
4570 return !in_array( $this->mNamespace
, $bannedNamespaces );
4575 * Returns the raw sort key to be used for categories, with the specified
4576 * prefix. This will be fed to Collation::getSortKey() to get a
4577 * binary sortkey that can be used for actual sorting.
4579 * @param string $prefix The prefix to be used, specified using
4580 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4584 public function getCategorySortkey( $prefix = '' ) {
4585 $unprefixed = $this->getText();
4587 // Anything that uses this hook should only depend
4588 // on the Title object passed in, and should probably
4589 // tell the users to run updateCollations.php --force
4590 // in order to re-sort existing category relations.
4591 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4592 if ( $prefix !== '' ) {
4593 # Separate with a line feed, so the unprefixed part is only used as
4594 # a tiebreaker when two pages have the exact same prefix.
4595 # In UCA, tab is the only character that can sort above LF
4596 # so we strip both of them from the original prefix.
4597 $prefix = strtr( $prefix, "\n\t", ' ' );
4598 return "$prefix\n$unprefixed";
4604 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4605 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4606 * the db, it will return NULL.
4608 * @return string|null|bool
4610 private function getDbPageLanguageCode() {
4611 global $wgPageLanguageUseDB;
4613 // check, if the page language could be saved in the database, and if so and
4614 // the value is not requested already, lookup the page language using LinkCache
4615 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4616 $linkCache = LinkCache
::singleton();
4617 $linkCache->addLinkObj( $this );
4618 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4621 return $this->mDbPageLanguage
;
4625 * Get the language in which the content of this page is written in
4626 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4627 * e.g. $wgLang (such as special pages, which are in the user language).
4632 public function getPageLanguage() {
4633 global $wgLang, $wgLanguageCode;
4634 if ( $this->isSpecialPage() ) {
4635 // special pages are in the user language
4639 // Checking if DB language is set
4640 $dbPageLanguage = $this->getDbPageLanguageCode();
4641 if ( $dbPageLanguage ) {
4642 return wfGetLangObj( $dbPageLanguage );
4645 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4646 // Note that this may depend on user settings, so the cache should
4647 // be only per-request.
4648 // NOTE: ContentHandler::getPageLanguage() may need to load the
4649 // content to determine the page language!
4650 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4652 $contentHandler = ContentHandler
::getForTitle( $this );
4653 $langObj = $contentHandler->getPageLanguage( $this );
4654 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4656 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4663 * Get the language in which the content of this page is written when
4664 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4665 * e.g. $wgLang (such as special pages, which are in the user language).
4670 public function getPageViewLanguage() {
4673 if ( $this->isSpecialPage() ) {
4674 // If the user chooses a variant, the content is actually
4675 // in a language whose code is the variant code.
4676 $variant = $wgLang->getPreferredVariant();
4677 if ( $wgLang->getCode() !== $variant ) {
4678 return Language
::factory( $variant );
4684 // Checking if DB language is set
4685 $dbPageLanguage = $this->getDbPageLanguageCode();
4686 if ( $dbPageLanguage ) {
4687 $pageLang = wfGetLangObj( $dbPageLanguage );
4688 $variant = $pageLang->getPreferredVariant();
4689 if ( $pageLang->getCode() !== $variant ) {
4690 $pageLang = Language
::factory( $variant );
4696 // @note Can't be cached persistently, depends on user settings.
4697 // @note ContentHandler::getPageViewLanguage() may need to load the
4698 // content to determine the page language!
4699 $contentHandler = ContentHandler
::getForTitle( $this );
4700 $pageLang = $contentHandler->getPageViewLanguage( $this );
4705 * Get a list of rendered edit notices for this page.
4707 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4708 * they will already be wrapped in paragraphs.
4711 * @param int $oldid Revision ID that's being edited
4714 public function getEditNotices( $oldid = 0 ) {
4717 // Optional notice for the entire namespace
4718 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4719 $msg = wfMessage( $editnotice_ns );
4720 if ( $msg->exists() ) {
4721 $html = $msg->parseAsBlock();
4722 // Edit notices may have complex logic, but output nothing (T91715)
4723 if ( trim( $html ) !== '' ) {
4724 $notices[$editnotice_ns] = Html
::rawElement(
4728 'mw-editnotice-namespace',
4729 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4736 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4737 // Optional notice for page itself and any parent page
4738 $parts = explode( '/', $this->getDBkey() );
4739 $editnotice_base = $editnotice_ns;
4740 while ( count( $parts ) > 0 ) {
4741 $editnotice_base .= '-' . array_shift( $parts );
4742 $msg = wfMessage( $editnotice_base );
4743 if ( $msg->exists() ) {
4744 $html = $msg->parseAsBlock();
4745 if ( trim( $html ) !== '' ) {
4746 $notices[$editnotice_base] = Html
::rawElement(
4750 'mw-editnotice-base',
4751 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4759 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4760 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4761 $msg = wfMessage( $editnoticeText );
4762 if ( $msg->exists() ) {
4763 $html = $msg->parseAsBlock();
4764 if ( trim( $html ) !== '' ) {
4765 $notices[$editnoticeText] = Html
::rawElement(
4769 'mw-editnotice-page',
4770 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4778 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4785 public function __sleep() {
4793 'mDefaultNamespace',
4797 public function __wakeup() {
4798 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4799 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4800 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );